Как обрабатывать токен доступа с истекшим сроком действия в ядре asp.net, используя токен обновления с OpenId Connect

Я настроил сервер ASOS OpenIdConnect с помощью основного приложения mvc asp.net, которое использует "Microsoft.AspNetCore.Authentication.OpenIdConnect": "1.0.0 и" Microsoft.AspNetCore.Authentication.Cookies ":" 1.0.0 ". Я проверил рабочий процесс "Код авторизации", и все работает.

Клиентское веб-приложение обрабатывает аутентификацию должным образом и создает файл cookie, в котором хранятся id_token, access_token и refresh_token.

Как заставить Microsoft.AspNetCore.Authentication.OpenIdConnect запрашивать новый access_token, когда он истекает?

Основное приложение mvc asp.net игнорирует просроченный access_token.

Я хотел бы, чтобы openidconnect видел просроченный access_token, а затем совершил вызов, используя токен обновления, чтобы получить новый access_token. Также следует обновить значения файлов cookie. Если запрос на обновление токена завершится неудачно, я ожидаю, что openidconnect "выйдет" из cookie (удалит его или что-то еще).

app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            AuthenticationScheme = "Cookies"
        });

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
        {
            ClientId = "myClient",
            ClientSecret = "secret_secret_secret",
            PostLogoutRedirectUri = "http://localhost:27933/",
            RequireHttpsMetadata = false,
            GetClaimsFromUserInfoEndpoint = true,
            SaveTokens = true,
            ResponseType = OpenIdConnectResponseType.Code,
            AuthenticationMethod = OpenIdConnectRedirectBehavior.RedirectGet,
            Authority = http://localhost:27933,
            MetadataAddress = "http://localhost:27933/connect/config",
            Scope = { "email", "roles", "offline_access" },
        });

2 ответа

Решение

Кажется, что в аутентификации openidconnect для ядра asp.net нет программирования для управления access_token на сервере после получения.

Я обнаружил, что могу перехватить событие проверки cookie и проверить, не истек ли токен доступа. Если так, сделайте ручной HTTP-вызов к конечной точке токена с grant_type=refresh_token.

Вызывая context.ShouldRenew = true; это приведет к обновлению cookie и его отправке обратно клиенту в ответе.

Я предоставил основание того, что я сделал, и постараюсь обновить этот ответ, как только вся работа будет решена.

app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            AuthenticationScheme = "Cookies",
            ExpireTimeSpan = new TimeSpan(0, 0, 20),
            SlidingExpiration = false,
            CookieName = "WebAuth",
            Events = new CookieAuthenticationEvents()
            {
                OnValidatePrincipal = context =>
                {
                    if (context.Properties.Items.ContainsKey(".Token.expires_at"))
                    {
                        var expire = DateTime.Parse(context.Properties.Items[".Token.expires_at"]);
                        if (expire > DateTime.Now) //TODO:change to check expires in next 5 mintues.
                        {
                            logger.Warn($"Access token has expired, user: {context.HttpContext.User.Identity.Name}");

                            //TODO: send refresh token to ASOS. Update tokens in context.Properties.Items
                            //context.Properties.Items["Token.access_token"] = newToken;
                            context.ShouldRenew = true;
                        }
                    }
                    return Task.FromResult(0);
                }
            }
        });

Следуя ответу @longday, мне удалось использовать этот код для принудительного обновления клиента без необходимости вручную запрашивать конечную точку открытого идентификатора:

OnValidatePrincipal = context =>
{
    if (context.Properties.Items.ContainsKey(".Token.expires_at"))
    {
        var expire = DateTime.Parse(context.Properties.Items[".Token.expires_at"]);
        if (expire > DateTime.Now) //TODO:change to check expires in next 5 mintues.
        {
            context.ShouldRenew = true;
            context.RejectPrincipal();
        }
    }

    return Task.FromResult(0);
}

Вы должны включить генерацию refresh_token, установив в файле startup.cs:

  • Установка значений в AuthorizationEndpointPath = "/connect/authorize"; // нужен для обновления
  • Установка значений в TokenEndpointPath = "/connect/token"; // стандартное имя конечной точки токена

Перед проверкой запроса токена в конце метода HandleTokenrequest у своего поставщика токенов убедитесь, что вы установили автономную область:

        // Call SetScopes with the list of scopes you want to grant
        // (specify offline_access to issue a refresh token).
        ticket.SetScopes(
            OpenIdConnectConstants.Scopes.Profile,
            OpenIdConnectConstants.Scopes.OfflineAccess);

Если все настроено правильно, вы должны получить ответ refresh_token при входе с паролем grant_type.

Затем от вашего клиента вы должны выполнить следующий запрос (я использую Aurelia):

refreshToken() {
    let baseUrl = yourbaseUrl;

    let data = "client_id=" + this.appState.clientId
               + "&grant_type=refresh_token"
               + "&refresh_token=myRefreshToken";

    return this.http.fetch(baseUrl + 'connect/token', {
        method: 'post',
        body : data,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json' 
        }
    });
}

и все, убедитесь, что ваш поставщик аутентификации в HandleRequestToken не пытается манипулировать запросом типа refresh_token:

    public override async Task HandleTokenRequest(HandleTokenRequestContext context)
    {
        if (context.Request.IsPasswordGrantType())
        {
            // Password type request processing only
            // code that shall not touch any refresh_token request
        }
        else if(!context.Request.IsRefreshTokenGrantType())
        {
            context.Reject(
                    error: OpenIdConnectConstants.Errors.InvalidGrant,
                    description: "Invalid grant type.");
            return;
        }

        return;
    }

Refresh_token должен просто проходить через этот метод и обрабатываться другим промежуточным программным обеспечением, которое обрабатывает refresh_token.

Если вам нужны более глубокие знания о том, что делает сервер аутентификации, вы можете взглянуть на код OpenIdConnectServerHandler:

https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/blob/master/src/AspNet.Security.OpenIdConnect.Server/OpenIdConnectServerHandler.Exchange.cs

На стороне клиента вы также должны иметь возможность обрабатывать автоматическое обновление токена, вот пример http-перехватчика для Angular 1.X, где один обрабатывает 401 ответ, обновляет токен, затем повторяет запрос:

'use strict';
app.factory('authInterceptorService',
    ['$q', '$injector', '$location', 'localStorageService',
    function ($q, $injector, $location, localStorageService) {

    var authInterceptorServiceFactory = {};
    var $http;

    var _request = function (config) {

        config.headers = config.headers || {};

        var authData = localStorageService.get('authorizationData');
        if (authData) {
            config.headers.Authorization = 'Bearer ' + authData.token;
        }

        return config;
    };

    var _responseError = function (rejection) {
        var deferred = $q.defer();
        if (rejection.status === 401) {
            var authService = $injector.get('authService');
            console.log("calling authService.refreshToken()");
            authService.refreshToken().then(function (response) {
                console.log("token refreshed, retrying to connect");
                _retryHttpRequest(rejection.config, deferred);
            }, function () {
                console.log("that didn't work, logging out.");
                authService.logOut();

                $location.path('/login');
                deferred.reject(rejection);
            });
        } else {
            deferred.reject(rejection);
        }
        return deferred.promise;
    };

    var _retryHttpRequest = function (config, deferred) {
        console.log('autorefresh');
        $http = $http || $injector.get('$http');
        $http(config).then(function (response) {
            deferred.resolve(response);
        },
        function (response) {
            deferred.reject(response);
        });
    }

    authInterceptorServiceFactory.request = _request;
    authInterceptorServiceFactory.responseError = _responseError;
    authInterceptorServiceFactory.retryHttpRequest = _retryHttpRequest;

    return authInterceptorServiceFactory;
}]);

И вот пример, который я только что сделал для Aurelia, на этот раз я завернул свой http-клиент в обработчик http, который проверяет, истек ли токен или нет. Если срок его действия истек, он сначала обновит токен, а затем выполнит запрос. Он использует обещание поддерживать согласованность интерфейса со службами данных на стороне клиента. Этот обработчик предоставляет тот же интерфейс, что и клиент aurelia-fetch.

import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import {AuthService} from './authService';

@inject(HttpClient, AuthService)
export class HttpHandler {

    constructor(httpClient, authService) {
        this.http = httpClient;
        this.authService = authService;
    }

    fetch(url, options){
        let _this = this;
        if(this.authService.tokenExpired()){
            console.log("token expired");
            return new Promise(
                function(resolve, reject) {
                    console.log("refreshing");
                    _this.authService.refreshToken()
                    .then(
                       function (response) {
                           console.log("token refreshed");
                        _this.http.fetch(url, options).then(
                            function (success) { 
                                console.log("call success", url);
                                resolve(success);
                            }, 
                            function (error) { 
                                console.log("call failed", url);
                                reject(error); 
                            }); 
                       }, function (error) {
                           console.log("token refresh failed");
                           reject(error);
                    });
                }
            );
        } 
        else {
            // token is not expired, we return the promise from the fetch client
            return this.http.fetch(url, options); 
        }
    }
}

Для jquery вы можете посмотреть jQuery oAuth:

https://github.com/esbenp/jquery-oauth

Надеюсь это поможет.

Другие вопросы по тегам