主頁 > .NET開發 > IdentityServer4原始碼決議_4_令牌發放介面

IdentityServer4原始碼決議_4_令牌發放介面

2020-09-16 00:01:59 .NET開發

目錄

  • IdentityServer4原始碼決議_1_專案結構
  • IdentityServer4原始碼決議_2_元資料介面
  • IdentityServer4原始碼決議_3_認證介面
  • IdentityServer4原始碼決議_4_令牌發放介面
  • IdentityServer4原始碼決議_5_查詢用戶資訊介面
  • [IdentityServer4原始碼決議_6_結束會話介面]
  • [IdentityServer4原始碼決議_7_查詢令牌資訊介面]
  • [IdentityServer4原始碼決議_8_撤銷令牌介面]

協議

Token介面

oidc服務需要提供token介面,提供AccessToken,IdToken,以及RefreshToken(可選),在授權碼模式下,token介面必須使用https,

請求

必須使用POST方法,使用x-www-form-urlencoded序列化引數,clientId:clientSecret使用Basic加密放在Authorization頭中

POST /token HTTP/1.1
Host: server.example.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW

grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https%3A%2F%2Fclient.example.org%2Fcb

請求校驗

認證服務必須校驗下列內容:

  • 驗證client是否頒發了秘鑰
  • 驗證為該客戶端頒發了授權碼
  • 驗證授權碼有效性
  • 如果可能的話,驗證授權碼是否被使用過
  • 驗證redirect_uri 與發起認證請求時的值一致

成功回應

在收到token請求,并校驗通過之后,認證服務回傳成功報文,報文包含了身份令牌和通行令牌,資料格式使用application/json,token_type必須回傳Bearer,其他型別token不在本協議范圍內,在OAuth2.0回應報文基礎上,oidc增加了id_tken,所有token包含了token或者其他敏感資訊的回應報文,必須包含以下回應頭,

Cache-Control no-store
Pragma no-cache

失敗回應

如果認證失敗回傳application/json格式錯誤訊息,狀態碼400

  HTTP/1.1 400 Bad Request
  Content-Type: application/json
  Cache-Control: no-store
  Pragma: no-cache

  {
   "error": "invalid_request"
  }

id token校驗

客戶端必須校驗回傳的id token, 校驗條件如下,對照這些條件,就可以更懂Microsoft.Authentication.OpenIdConnect里面的代碼了,要做的事情很多,

  1. 如果id token被加密,使用客戶端注冊時候約定的秘鑰和演算法解密,如果約定了加密方式,id token未被加密,客戶端應該拒絕,
  2. 簽發方標識必須與iss宣告一致
  3. 客戶端必須校驗aud宣告包含了它的客戶端id,如果id token未回傳正確的audience或者反悔了不被新人的audience,應該拒絕
  4. 如果id token包含多個audience,需要校驗是否有azp宣告,azp即Authorized party,標識被授權的client,
  5. 如果包含azp宣告,客戶端需要校驗其值是否為自己的客戶端id
  6. 如果id token由token介面直接頒發給客戶端(授權碼模式就是如此),客戶端必須根據alg引數值的演算法驗證簽名,客戶端必須使用簽發方提供的秘鑰,
  7. alg值默認為RS256,客戶端可以在注冊的時候使用id_token_signed_response_alg引數指定配置,
  8. 如果jwt的alg頭使用了基于mac地址的加密演算法,如HS256, HS384,HS512,aud宣告中的位元組會用作驗簽,(意思是會把mac地址相關資訊寫在aud宣告上?)
  9. The current time MUST be before the time represented by the exp Claim.
    當前時間必須早于exp(token過期時間),
  10. iat(簽發時間)可以用于拒絕過早、或者過于頻繁簽發的token,可以用于預防重放攻擊,可接受時間范圍由客戶端自行決定,
  11. 如果認證請求包含了nonce引數,客戶端必須交驗認證回應中回傳的nonce值是否一致,防止重放攻擊,
  12. 如果客戶端請求了acr宣告(Authentication Context Class Reference,認證會話背景關系,用于表示當前認證會話),必須交驗acr值是否合法,
  13. 如果客戶端請求了auth_time宣告,客戶端應該校驗認證時間是否已經超出,是否需要重新認證,

access token校驗

如果id_token中包含了at_hash宣告,需要做下面的校驗,at_hash標明了access_token和id_token之間的會話關聯關系,做這個校驗可以防跨站偽造,

  1. 用idtoken的alg頭標明的演算法加密access_token,比如alg位RS256,則是用HSA-256演算法加密,
  2. 取hash值左邊一般使用base64url加密
  3. id token中的at_hash值必須跟上個步驟得到的值一致

校驗規則很多,了解一下即可,絕大部分屬于客戶端需要做的部分,絕大部分跟安全有關,這一塊的實作可以參考Microsoft.Authentication.OpenIdConnect,這是客戶端的實作,我們現在看的IdentityServer是認證服務端的實作,

原始碼

五種授權模式

有下面幾種授權模式可以請求token介面

  • 授權碼模式:最常用的code換token
  • 混合模式:混合模式是授權碼模式+簡化模式混合使用的方式,在用授權碼code找token介面換通行/身份令牌的邏輯與授權碼模式的邏輯是一樣的,idsv4中,混合模式沒有自己的單獨實作,只是把授權碼+簡化模式的代碼同時呼叫,
  • 客戶端密鑰模式:一般用于完全信任的內部系統,密鑰換取access_token,由于沒有用戶參與,scope包含open_id是非法的
  • 用戶名密碼模式:一般用于第三方對接、無界面互動場景,即username+password換token/id_token,password不一定是密碼,也可以是驗證碼或其他的什么東西,這個完全取決于開發自己的實作
  • 設備流模式(略)

注意:簡化模式所有的token都是由認證介面(authorize)一次性回傳的,不能使用token介面,

校驗請求方法

token介面僅允許POST方法,Content-Type必須為application/x-www-form-urlencoded,否則拋出InvalidRequest錯誤,

public async Task<IEndpointResult> ProcessAsync(HttpContext context)
    {
        _logger.LogTrace("Processing token request.");

        // validate HTTP
        if (!HttpMethods.IsPost(context.Request.Method) || !context.Request.HasFormContentType)
        {
            _logger.LogWarning("Invalid HTTP request for token endpoint");
            return Error(OidcConstants.TokenErrors.InvalidRequest);
        }

        return await ProcessTokenRequestAsync(context);
    }

處理流程

  • 校驗客戶端
  • 校驗請求引數
  • 創建回傳值
  • 回傳結果
private async Task<IEndpointResult> ProcessTokenRequestAsync(HttpContext context)
{
    _logger.LogDebug("Start token request.");

    // validate client
    var clientResult = await _clientValidator.ValidateAsync(context);

    if (clientResult.Client == null)
    {
        return Error(OidcConstants.TokenErrors.InvalidClient);
    }

    // validate request
    var form = (await context.Request.ReadFormAsync()).AsNameValueCollection();
    _logger.LogTrace("Calling into token request validator: {type}", _requestValidator.GetType().FullName);
    var requestResult = await _requestValidator.ValidateRequestAsync(form, clientResult);

    if (requestResult.IsError)
    {
        await _events.RaiseAsync(new TokenIssuedFailureEvent(requestResult));
        return Error(requestResult.Error, requestResult.ErrorDescription, requestResult.CustomResponse);
    }

    // create response
    _logger.LogTrace("Calling into token request response generator: {type}", _responseGenerator.GetType().FullName);
    var response = await _responseGenerator.ProcessAsync(requestResult);

    await _events.RaiseAsync(new TokenIssuedSuccessEvent(response, requestResult));
    LogTokens(response, requestResult);

    // return result
    _logger.LogDebug("Token request success.");
    return new TokenResult(response);
}

校驗客戶端

  • 解碼客戶端秘鑰,對應的處理類是BasicAuthenticationSecretParser,客戶端id和秘鑰用base64url加密方法放在Authorzaition頭上,base64url基本是明文的,因為授權碼換token是后端進行的,所以安全性沒有問題
  • 解碼得到客戶端id和秘鑰之后,跟store對比校驗客戶端是否存在,秘鑰是否一致,
public async Task<ClientSecretValidationResult> ValidateAsync(HttpContext context)
{
    _logger.LogDebug("Start client validation");

    var fail = new ClientSecretValidationResult
    {
        IsError = true
    };

    var parsedSecret = await _parser.ParseAsync(context);
    if (parsedSecret == null)
    {
        await RaiseFailureEventAsync("unknown", "No client id found");

        _logger.LogError("No client identifier found");
        return fail;
    }

    // load client
    var client = await _clients.FindEnabledClientByIdAsync(parsedSecret.Id);
    if (client == null)
    {
        await RaiseFailureEventAsync(parsedSecret.Id, "Unknown client");

        _logger.LogError("No client with id '{clientId}' found. aborting", parsedSecret.Id);
        return fail;
    }

    SecretValidationResult secretValidationResult = null;
    if (!client.RequireClientSecret || client.IsImplicitOnly())
    {
        _logger.LogDebug("Public Client - skipping secret validation success");
    }
    else
    {
        secretValidationResult = await _validator.ValidateAsync(parsedSecret, client.ClientSecrets);
        if (secretValidationResult.Success == false)
        {
            await RaiseFailureEventAsync(client.ClientId, "Invalid client secret");
            _logger.LogError("Client secret validation failed for client: {clientId}.", client.ClientId);

            return fail;
        }
    }

    _logger.LogDebug("Client validation success");

    var success = new ClientSecretValidationResult
    {
        IsError = false,
        Client = client,
        Secret = parsedSecret,
        Confirmation = secretValidationResult?.Confirmation
    };

    await RaiseSuccessEventAsync(client.ClientId, parsedSecret.Type);
    return success;
}

校驗請求引數

  • 客戶端的PortocalType必須位oidc,否則報錯InvalidClient
  • 校驗GrantType,必填,長度不能超過100,
  • GrantType默認支持以下幾種型別,還可以自定義GrantType
    • authorization_code:授權碼換token
    • client_credentials:客戶端秘鑰換token
    • password:用戶名密碼換token
    • refresn_token:重繪令牌換token
    • urn:ietf:params:oauth:grant-type:device_code:deviceflow,略
public async Task<TokenRequestValidationResult> ValidateRequestAsync(NameValueCollection parameters, ClientSecretValidationResult clientValidationResult)
{
    _logger.LogDebug("Start token request validation");

    _validatedRequest = new ValidatedTokenRequest
    {
        Raw = parameters ?? throw new ArgumentNullException(nameof(parameters)),
        Options = _options
    };

    if (clientValidationResult == null) throw new ArgumentNullException(nameof(clientValidationResult));

    _validatedRequest.SetClient(clientValidationResult.Client, clientValidationResult.Secret, clientValidationResult.Confirmation);

    /////////////////////////////////////////////
    // check client protocol type
    /////////////////////////////////////////////
    if (_validatedRequest.Client.ProtocolType != IdentityServerConstants.ProtocolTypes.OpenIdConnect)
    {
        LogError("Invalid protocol type for client",
            new
            {
                clientId = _validatedRequest.Client.ClientId,
                expectedProtocolType = IdentityServerConstants.ProtocolTypes.OpenIdConnect,
                actualProtocolType = _validatedRequest.Client.ProtocolType
            });

        return Invalid(OidcConstants.TokenErrors.InvalidClient);
    }

    /////////////////////////////////////////////
    // check grant type
    /////////////////////////////////////////////
    var grantType = parameters.Get(OidcConstants.TokenRequest.GrantType);
    if (grantType.IsMissing())
    {
        LogError("Grant type is missing");
        return Invalid(OidcConstants.TokenErrors.UnsupportedGrantType);
    }

    if (grantType.Length > _options.InputLengthRestrictions.GrantType)
    {
        LogError("Grant type is too long");
        return Invalid(OidcConstants.TokenErrors.UnsupportedGrantType);
    }

    _validatedRequest.GrantType = grantType;

    switch (grantType)
    {
        case OidcConstants.GrantTypes.AuthorizationCode:
            return await RunValidationAsync(ValidateAuthorizationCodeRequestAsync, parameters);
        case OidcConstants.GrantTypes.ClientCredentials:
            return await RunValidationAsync(ValidateClientCredentialsRequestAsync, parameters);
        case OidcConstants.GrantTypes.Password:
            return await RunValidationAsync(ValidateResourceOwnerCredentialRequestAsync, parameters);
        case OidcConstants.GrantTypes.RefreshToken:
            return await RunValidationAsync(ValidateRefreshTokenRequestAsync, parameters);
        case OidcConstants.GrantTypes.DeviceCode:
            return await RunValidationAsync(ValidateDeviceCodeRequestAsync, parameters);
        default:
            return await RunValidationAsync(ValidateExtensionGrantRequestAsync, parameters);
    }
}

引數校驗 - 授權碼模式

  • 客戶端AllowedGrantTypes必須包含authorization_code或者hybrid,否則報錯UnauthorizedClient,
  • code必填,code長度不能超過100
  • 客戶端傳過來的code只是授權碼的id,從store中取出來授權碼物件,如果不存在回傳錯誤InvalidGrant
  • 從store中移除授權碼,此處實作了code只是用一次
  • 如果授權碼超出有效時長,回傳錯誤invalidGrant
  • 校驗授權碼物件的客戶端id與當前客戶端是否一致
  • redirect_uri必填,且必須與授權碼物件保存的redirect_uri一致,否則回傳錯誤UnauthorizedClient
  • 如果請求中沒有任何scope,回傳錯誤invalidRequest
  • 判斷用戶是否啟用,這個判斷是由可插拔服務IProfileService的IsActive方法來實作的,開發可以注入自己的實作,如果用戶禁用將回傳錯誤InvalidGrant,
private async Task<TokenRequestValidationResult> ValidateAuthorizationCodeRequestAsync(NameValueCollection parameters)
    {
        _logger.LogDebug("Start validation of authorization code token request");

        /////////////////////////////////////////////
        // check if client is authorized for grant type
        /////////////////////////////////////////////
        if (!_validatedRequest.Client.AllowedGrantTypes.ToList().Contains(GrantType.AuthorizationCode) &&
            !_validatedRequest.Client.AllowedGrantTypes.ToList().Contains(GrantType.Hybrid))
        {
            LogError("Client not authorized for code flow");
            return Invalid(OidcConstants.TokenErrors.UnauthorizedClient);
        }

        /////////////////////////////////////////////
        // validate authorization code
        /////////////////////////////////////////////
        var code = parameters.Get(OidcConstants.TokenRequest.Code);
        if (code.IsMissing())
        {
            LogError("Authorization code is missing");
            return Invalid(OidcConstants.TokenErrors.InvalidGrant);
        }

        if (code.Length > _options.InputLengthRestrictions.AuthorizationCode)
        {
            LogError("Authorization code is too long");
            return Invalid(OidcConstants.TokenErrors.InvalidGrant);
        }

        _validatedRequest.AuthorizationCodeHandle = code;

        var authZcode = await _authorizationCodeStore.GetAuthorizationCodeAsync(code);
        if (authZcode == null)
        {
            LogError("Invalid authorization code", new { code });
            return Invalid(OidcConstants.TokenErrors.InvalidGrant);
        }

        await _authorizationCodeStore.RemoveAuthorizationCodeAsync(code);

        if (authZcode.CreationTime.HasExceeded(authZcode.Lifetime, _clock.UtcNow.UtcDateTime))
        {
            LogError("Authorization code expired", new { code });
            return Invalid(OidcConstants.TokenErrors.InvalidGrant);
        }

        /////////////////////////////////////////////
        // populate session id
        /////////////////////////////////////////////
        if (authZcode.SessionId.IsPresent())
        {
            _validatedRequest.SessionId = authZcode.SessionId;
        }

        /////////////////////////////////////////////
        // validate client binding
        /////////////////////////////////////////////
        if (authZcode.ClientId != _validatedRequest.Client.ClientId)
        {
            LogError("Client is trying to use a code from a different client", new { clientId = _validatedRequest.Client.ClientId, codeClient = authZcode.ClientId });
            return Invalid(OidcConstants.TokenErrors.InvalidGrant);
        }

        /////////////////////////////////////////////
        // validate code expiration
        /////////////////////////////////////////////
        if (authZcode.CreationTime.HasExceeded(_validatedRequest.Client.AuthorizationCodeLifetime, _clock.UtcNow.UtcDateTime))
        {
            LogError("Authorization code is expired");
            return Invalid(OidcConstants.TokenErrors.InvalidGrant);
        }

        _validatedRequest.AuthorizationCode = authZcode;
        _validatedRequest.Subject = authZcode.Subject;

        /////////////////////////////////////////////
        // validate redirect_uri
        /////////////////////////////////////////////
        var redirectUri = parameters.Get(OidcConstants.TokenRequest.RedirectUri);
        if (redirectUri.IsMissing())
        {
            LogError("Redirect URI is missing");
            return Invalid(OidcConstants.TokenErrors.UnauthorizedClient);
        }

        if (redirectUri.Equals(_validatedRequest.AuthorizationCode.RedirectUri, StringComparison.Ordinal) == false)
        {
            LogError("Invalid redirect_uri", new { redirectUri, expectedRedirectUri = _validatedRequest.AuthorizationCode.RedirectUri });
            return Invalid(OidcConstants.TokenErrors.UnauthorizedClient);
        }

        /////////////////////////////////////////////
        // validate scopes are present
        /////////////////////////////////////////////
        if (_validatedRequest.AuthorizationCode.RequestedScopes == null ||
            !_validatedRequest.AuthorizationCode.RequestedScopes.Any())
        {
            LogError("Authorization code has no associated scopes");
            return Invalid(OidcConstants.TokenErrors.InvalidRequest);
        }

        /////////////////////////////////////////////
        // validate PKCE parameters
        /////////////////////////////////////////////
        var codeVerifier = parameters.Get(OidcConstants.TokenRequest.CodeVerifier);
        if (_validatedRequest.Client.RequirePkce || _validatedRequest.AuthorizationCode.CodeChallenge.IsPresent())
        {
            _logger.LogDebug("Client required a proof key for code exchange. Starting PKCE validation");

            var proofKeyResult = ValidateAuthorizationCodeWithProofKeyParameters(codeVerifier, _validatedRequest.AuthorizationCode);
            if (proofKeyResult.IsError)
            {
                return proofKeyResult;
            }

            _validatedRequest.CodeVerifier = codeVerifier;
        }
        else
        {
            if (codeVerifier.IsPresent())
            {
                LogError("Unexpected code_verifier: {codeVerifier}. This happens when the client is trying to use PKCE, but it is not enabled. Set RequirePkce to true.", codeVerifier);
                return Invalid(OidcConstants.TokenErrors.InvalidGrant);
            }
        }

        /////////////////////////////////////////////
        // make sure user is enabled
        /////////////////////////////////////////////
        var isActiveCtx = new IsActiveContext(_validatedRequest.AuthorizationCode.Subject, _validatedRequest.Client, IdentityServerConstants.ProfileIsActiveCallers.AuthorizationCodeValidation);
        await _profile.IsActiveAsync(isActiveCtx);

        if (isActiveCtx.IsActive == false)
        {
            LogError("User has been disabled", new { subjectId = _validatedRequest.AuthorizationCode.Subject.GetSubjectId() });
            return Invalid(OidcConstants.TokenErrors.InvalidGrant);
        }

        _logger.LogDebug("Validation of authorization code token request success");

        return Valid();
    }

引數校驗 - 客戶端秘鑰模式

  • 校驗Client是否允許使用客戶端秘鑰認證模式
  • 校驗客戶端是否允許訪問請求的授權范圍scope
  • scope中包含openid的話回傳錯誤invlidScope,因為本模式沒有涉及用戶資訊
  • cope中包含offline_access則回傳錯誤InvalidScope,本模式不允許使用refresh_token
private async Task<TokenRequestValidationResult> ValidateClientCredentialsRequestAsync(NameValueCollection parameters)
    {
        _logger.LogDebug("Start client credentials token request validation");

        /////////////////////////////////////////////
        // check if client is authorized for grant type
        /////////////////////////////////////////////
        if (!_validatedRequest.Client.AllowedGrantTypes.ToList().Contains(GrantType.ClientCredentials))
        {
            LogError("Client not authorized for client credentials flow, check the AllowedGrantTypes setting", new { clientId = _validatedRequest.Client.ClientId });
            return Invalid(OidcConstants.TokenErrors.UnauthorizedClient);
        }

        /////////////////////////////////////////////
        // check if client is allowed to request scopes
        /////////////////////////////////////////////
        if (!await ValidateRequestedScopesAsync(parameters, ignoreImplicitIdentityScopes: true, ignoreImplicitOfflineAccess: true))
        {
            return Invalid(OidcConstants.TokenErrors.InvalidScope);
        }

        if (_validatedRequest.ValidatedScopes.ContainsOpenIdScopes)
        {
            LogError("Client cannot request OpenID scopes in client credentials flow", new { clientId = _validatedRequest.Client.ClientId });
            return Invalid(OidcConstants.TokenErrors.InvalidScope);
        }

        if (_validatedRequest.ValidatedScopes.ContainsOfflineAccessScope)
        {
            LogError("Client cannot request a refresh token in client credentials flow", new { clientId = _validatedRequest.Client.ClientId });
            return Invalid(OidcConstants.TokenErrors.InvalidScope);
        }

        _logger.LogDebug("{clientId} credentials token request validation success", _validatedRequest.Client.ClientId);
        return Valid();
    }

引數校驗 - 用戶名密碼模式

  • 校驗客戶端是否允許使用用戶名密碼模式,校驗失敗回傳UnauthoriedClient錯誤
  • 校驗客戶端是否有權訪問所請求的所有scope,校驗失敗回傳InvalidScope錯誤
  • 從請求中獲取username和password引數,未提供username回傳InvalidGrant錯誤,未提供password則設定password位空值
  • username和password長度不能超過100,否則回傳InvalidGrant錯誤
  • 使用IResourceOwnerPasswordValidator校驗username和password,此介面需要開發實作后注入,否則會拋出例外
  • GrantValidationResult的Subject不能為null,因此開發的IResourceOwnerPasswordValidator實作,校驗成功后必須給GrantValidationResult賦值
  • 校驗用戶是否禁用,根據可插拔服務IProfileService的IsAcrtive方法判斷,如果禁用回傳IvalidGrant錯誤,
private async Task<TokenRequestValidationResult> ValidateResourceOwnerCredentialRequestAsync(NameValueCollection parameters)
{
    _logger.LogDebug("Start resource owner password token request validation");

    /////////////////////////////////////////////
    // check if client is authorized for grant type
    /////////////////////////////////////////////
    if (!_validatedRequest.Client.AllowedGrantTypes.Contains(GrantType.ResourceOwnerPassword))
    {
        LogError("Client not authorized for resource owner flow, check the AllowedGrantTypes setting", new { client_id = _validatedRequest.Client.ClientId });
        return Invalid(OidcConstants.TokenErrors.UnauthorizedClient);
    }

    /////////////////////////////////////////////
    // check if client is allowed to request scopes
    /////////////////////////////////////////////
    if (!(await ValidateRequestedScopesAsync(parameters)))
    {
        return Invalid(OidcConstants.TokenErrors.InvalidScope);
    }

    /////////////////////////////////////////////
    // check resource owner credentials
    /////////////////////////////////////////////
    var userName = parameters.Get(OidcConstants.TokenRequest.UserName);
    var password = parameters.Get(OidcConstants.TokenRequest.Password);

    if (userName.IsMissing())
    {
        LogError("Username is missing");
        return Invalid(OidcConstants.TokenErrors.InvalidGrant);
    }

    if (password.IsMissing())
    {
        password = "";
    }

    if (userName.Length > _options.InputLengthRestrictions.UserName ||
        password.Length > _options.InputLengthRestrictions.Password)
    {
        LogError("Username or password too long");
        return Invalid(OidcConstants.TokenErrors.InvalidGrant);
    }

    _validatedRequest.UserName = userName;


    /////////////////////////////////////////////
    // authenticate user
    /////////////////////////////////////////////
    var resourceOwnerContext = new ResourceOwnerPasswordValidationContext
    {
        UserName = userName,
        Password = password,
        Request = _validatedRequest
    };
    await _resourceOwnerValidator.ValidateAsync(resourceOwnerContext);

    if (resourceOwnerContext.Result.IsError)
    {
        // protect against bad validator implementations
        resourceOwnerContext.Result.Error = resourceOwnerContext.Result.Error ?? OidcConstants.TokenErrors.InvalidGrant;

        if (resourceOwnerContext.Result.Error == OidcConstants.TokenErrors.UnsupportedGrantType)
        {
            LogError("Resource owner password credential grant type not supported");
            await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, "password grant type not supported", resourceOwnerContext.Request.Client.ClientId);

            return Invalid(OidcConstants.TokenErrors.UnsupportedGrantType, customResponse: resourceOwnerContext.Result.CustomResponse);
        }

        var errorDescription = "invalid_username_or_password";

        if (resourceOwnerContext.Result.ErrorDescription.IsPresent())
        {
            errorDescription = resourceOwnerContext.Result.ErrorDescription;
        }

        LogInformation("User authentication failed: ", errorDescription ?? resourceOwnerContext.Result.Error);
        await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, errorDescription, resourceOwnerContext.Request.Client.ClientId);

        return Invalid(resourceOwnerContext.Result.Error, errorDescription, resourceOwnerContext.Result.CustomResponse);
    }

    if (resourceOwnerContext.Result.Subject == null)
    {
        var error = "User authentication failed: no principal returned";
        LogError(error);
        await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, error, resourceOwnerContext.Request.Client.ClientId);

        return Invalid(OidcConstants.TokenErrors.InvalidGrant);
    }

    /////////////////////////////////////////////
    // make sure user is enabled
    /////////////////////////////////////////////
    var isActiveCtx = new IsActiveContext(resourceOwnerContext.Result.Subject, _validatedRequest.Client, IdentityServerConstants.ProfileIsActiveCallers.ResourceOwnerValidation);
    await _profile.IsActiveAsync(isActiveCtx);

    if (isActiveCtx.IsActive == false)
    {
        LogError("User has been disabled", new { subjectId = resourceOwnerContext.Result.Subject.GetSubjectId() });
        await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, "user is inactive", resourceOwnerContext.Request.Client.ClientId);

        return Invalid(OidcConstants.TokenErrors.InvalidGrant);
    }

    _validatedRequest.UserName = userName;
    _validatedRequest.Subject = resourceOwnerContext.Result.Subject;

    await RaiseSuccessfulResourceOwnerAuthenticationEventAsync(userName, resourceOwnerContext.Result.Subject.GetSubjectId(), resourceOwnerContext.Request.Client.ClientId);
    _logger.LogDebug("Resource owner password token request validation success.");
    return Valid(resourceOwnerContext.Result.CustomResponse);
}

引數校驗 - RefreshToken

RefreshToken-重繪令牌,顧名思義,用于重繪通行令牌的憑證,擁有offline_access權限的客戶端可以使用重繪令牌,只有授權碼、混合流程等由后端參與的授權模式才允許使用重繪令牌,

  • 從請求中獲取refresh_token引數值,如果為空則回傳InvalidRequest錯誤
  • 如果重繪令牌長度超過100,回傳InvalidGrant錯誤
  • 判斷重繪令牌是否存在且有效
    • 是否能從store中查詢到重繪令牌物件
    • 校驗重繪令牌是否過期
    • 校驗重繪令牌是否屬于當前客戶端
    • 校驗客戶端是否仍然有offline_access權限
    • 校驗用戶是否被禁用
private async Task<TokenRequestValidationResult> ValidateRefreshTokenRequestAsync(NameValueCollection parameters)
{
    _logger.LogDebug("Start validation of refresh token request");

    var refreshTokenHandle = parameters.Get(OidcConstants.TokenRequest.RefreshToken);
    if (refreshTokenHandle.IsMissing())
    {
        LogError("Refresh token is missing");
        return Invalid(OidcConstants.TokenErrors.InvalidRequest);
    }

    if (refreshTokenHandle.Length > _options.InputLengthRestrictions.RefreshToken)
    {
        LogError("Refresh token too long");
        return Invalid(OidcConstants.TokenErrors.InvalidGrant);
    }

    var result = await _tokenValidator.ValidateRefreshTokenAsync(refreshTokenHandle, _validatedRequest.Client);

    if (result.IsError)
    {
        LogWarning("Refresh token validation failed. aborting");
        return Invalid(OidcConstants.TokenErrors.InvalidGrant);
    }

    _validatedRequest.RefreshToken = result.RefreshToken;
    _validatedRequest.RefreshTokenHandle = refreshTokenHandle;
    _validatedRequest.Subject = result.RefreshToken.Subject;

    _logger.LogDebug("Validation of refresh token request success");
    return Valid();
}

生成回應報文 - 授權碼模式

  • 生成accessToken和refreshToken
    • 通行令牌由ITokenService介面,默認實作DefaultTokenService的CreateAccessTokenAsync方法生成
    • 如果請求了offline_access才生成refresh_token
    • 如果code是oidc授權碼,生成id_token,DefaultTokenService的CreateIdentityTokenAsync方法生成Token物件,CreateSecurityTokenAsync方法將Token物件加密為jwt,
protected virtual async Task<TokenResponse> ProcessAuthorizationCodeRequestAsync(TokenRequestValidationResult request)
    {
        Logger.LogTrace("Creating response for authorization code request");

        //////////////////////////
        // access token
        /////////////////////////
        (var accessToken, var refreshToken) = await CreateAccessTokenAsync(request.ValidatedRequest);
        var response = new TokenResponse
        {
            AccessToken = accessToken,
            AccessTokenLifetime = request.ValidatedRequest.AccessTokenLifetime,
            Custom = request.CustomResponse,
            Scope = request.ValidatedRequest.AuthorizationCode.RequestedScopes.ToSpaceSeparatedString(),
        };

        //////////////////////////
        // refresh token
        /////////////////////////
        if (refreshToken.IsPresent())
        {
            response.RefreshToken = refreshToken;
        }

        //////////////////////////
        // id token
        /////////////////////////
        if (request.ValidatedRequest.AuthorizationCode.IsOpenId)
        {
            // load the client that belongs to the authorization code
            Client client = null;
            if (request.ValidatedRequest.AuthorizationCode.ClientId != null)
            {
                client = await Clients.FindEnabledClientByIdAsync(request.ValidatedRequest.AuthorizationCode.ClientId);
            }
            if (client == null)
            {
                throw new InvalidOperationException("Client does not exist anymore.");
            }

            var resources = await Resources.FindEnabledResourcesByScopeAsync(request.ValidatedRequest.AuthorizationCode.RequestedScopes);

            var tokenRequest = new TokenCreationRequest
            {
                Subject = request.ValidatedRequest.AuthorizationCode.Subject,
                Resources = resources,
                Nonce = request.ValidatedRequest.AuthorizationCode.Nonce,
                AccessTokenToHash = response.AccessToken,
                StateHash = request.ValidatedRequest.AuthorizationCode.StateHash,
                ValidatedRequest = request.ValidatedRequest
            };

            var idToken = await TokenService.CreateIdentityTokenAsync(tokenRequest);
            var jwt = await TokenService.CreateSecurityTokenAsync(idToken);
            response.IdentityToken = jwt;
        }

        return response;
    }

生成回應報文 - 客戶端密鑰模式

  • 僅生成accessToken
protected virtual Task<TokenResponse> ProcessClientCredentialsRequestAsync(TokenRequestValidationResult request)
{
    Logger.LogTrace("Creating response for client credentials request");

    return ProcessTokenRequestAsync(request);
}

protected virtual async Task<TokenResponse> ProcessTokenRequestAsync(TokenRequestValidationResult validationResult)
    {
        (var accessToken, var refreshToken) = await CreateAccessTokenAsync(validationResult.ValidatedRequest);
        var response = new TokenResponse
        {
            AccessToken = accessToken,
            AccessTokenLifetime = validationResult.ValidatedRequest.AccessTokenLifetime,
            Custom = validationResult.CustomResponse,
            Scope = validationResult.ValidatedRequest.Scopes.ToSpaceSeparatedString()
        };

        if (refreshToken.IsPresent())
        {
            response.RefreshToken = refreshToken;
        }

        return response;
    }

生成回應報文 - 用戶名密碼模式

  • 生成accessToken
  • 如果申請了offline_access且有權限,同時回傳refresh_token
  • 不會回傳id_token,我理解的是授權碼等模式是有限授權,需要code換id_token,才能拿到用戶id以及其他的基本資訊,而密碼模式是完全信任授權,賬號密碼都給你了,還整id_token干嘛,你要啥資訊,自己實作IResourceOwnerPasswordValidator,自己去庫里取就完事了,還要啥自行車,
protected virtual Task<TokenResponse> ProcessPasswordRequestAsync(TokenRequestValidationResult request)
    {
        Logger.LogTrace("Creating response for password request");

        return ProcessTokenRequestAsync(request);
    }

生成回應報文 - 重繪令牌

  • 從請求中取出舊通行令牌
  • 判斷客戶端配置UpdateAccessTokenClaimsOnRefresh-是否在重繪令牌的時候更新通行令牌的claims,默認false,如果為true,則創建新的token物件,否則使用舊的token,只是重繪token的創建時間和有效時間,
  • 判斷客戶端配置RefreshTokenUsage - 重繪令牌用法,0:ReUse可重復使用 1:OnTimeOnly一次性,默認1,如果是一次性的話,從store中洗掉舊的重繪令牌,創建新的重繪令牌,
  • 判斷客戶端配置RefreshTokenExpiration - 重繪令牌過期型別,0:Sliding,1:Absolute,默認1,如果是0,需要重新計算相對時間,
  • 如果重繪令牌請求包含了任意身份資源,創建新的身份令牌,
protected virtual async Task<TokenResponse> ProcessRefreshTokenRequestAsync(TokenRequestValidationResult request)
    {
        Logger.LogTrace("Creating response for refresh token request");

        var oldAccessToken = request.ValidatedRequest.RefreshToken.AccessToken;
        string accessTokenString;

        if (request.ValidatedRequest.Client.UpdateAccessTokenClaimsOnRefresh)
        {
            var subject = request.ValidatedRequest.RefreshToken.Subject;

            var creationRequest = new TokenCreationRequest
            {
                Subject = subject,
                ValidatedRequest = request.ValidatedRequest,
                Resources = await Resources.FindEnabledResourcesByScopeAsync(oldAccessToken.Scopes)
            };

            var newAccessToken = await TokenService.CreateAccessTokenAsync(creationRequest);
            accessTokenString = await TokenService.CreateSecurityTokenAsync(newAccessToken);
        }
        else
        {
            oldAccessToken.CreationTime = Clock.UtcNow.UtcDateTime;
            oldAccessToken.Lifetime = request.ValidatedRequest.AccessTokenLifetime;

            accessTokenString = await TokenService.CreateSecurityTokenAsync(oldAccessToken);
        }

        var handle = await RefreshTokenService.UpdateRefreshTokenAsync(request.ValidatedRequest.RefreshTokenHandle, request.ValidatedRequest.RefreshToken, request.ValidatedRequest.Client);

        return new TokenResponse
        {
            IdentityToken = await CreateIdTokenFromRefreshTokenRequestAsync(request.ValidatedRequest, accessTokenString),
            AccessToken = accessTokenString,
            AccessTokenLifetime = request.ValidatedRequest.AccessTokenLifetime,
            RefreshToken = handle,
            Custom = request.CustomResponse,
            Scope = request.ValidatedRequest.RefreshToken.Scopes.ToSpaceSeparatedString()
        };
    }

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/50974.html

標籤:.NET Core

上一篇:.net Core專案發布到Docker for Windows

下一篇:遠程終端管理和檢測系統

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more