IdentityServer4 实现自定义 GrantType 授权模式
OAuth 2.0 默認四種授權模式(GrantType):
授權碼模式(authorization_code)
簡化模式(implicit)
密碼模式(password)
客戶端模式(client_credentials)
使用 IdentityServer4,我們可以自定義授權模式嗎?答案是可以的,比如我們自定義實現一個anonymous授權模式(匿名訪問)。
創建AnonymousGrantValidator(繼承IExtensionGrantValidator):
public class AnonymousGrantValidator : IExtensionGrantValidator{ ??private readonly ITokenValidator _validator; ?
?
??public AnonymousGrantValidator(ITokenValidator validator) ? ?{_validator = validator;} ?
???public string GrantType => "anonymous"; ?
???public async Task ValidateAsync(ExtensionGrantValidationContext context) ? ?{ ? ? ? ?//var userToken = context.Request.Raw.Get("token");//if (string.IsNullOrEmpty(userToken))//{// ? ?context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);// ? ?return;//}//var result = await _validator.ValidateAccessTokenAsync(userToken);//if (result.IsError)//{// ? ?context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);// ? ?return;//}// get user's identity//var sub = result.Claims.FirstOrDefault(c => c.Type == "sub").Value;var claims = new List<Claim>() { new Claim("role", GrantType) }; // Claim 用于配置服務站點 [Authorize("anonymous")]context.Result = new GrantValidationResult(GrantType, GrantType, claims);} }
修改Client配置:
new Client {ClientId = "client1",AllowedGrantTypes = GrantTypes.List(GrantTypes.ResourceOwnerPassword.FirstOrDefault(), "anonymous"), //一個 Client 可以配置多個 GrantTypeAllowOfflineAccess = true,AccessTokenLifetime = 3600 * 6, //6小時SlidingRefreshTokenLifetime = 1296000, //15天ClientSecrets ={ ? ? ? ?new Secret("123".Sha256())},AllowedScopes = new List<string>{ ? ? ? ?"api2"} }DI 增加注入對象:
builder.AddExtensionGrantValidator<AnonymousGrantValidator>();調用示例代碼:
public async Task<TokenResponse> AnonymousAsync(string userToken){ ? ?var payload = new{token = userToken}; ? ?// create token clientvar client = new TokenClient(disco.TokenEndpoint, "client1", "123"); ? ?// send custom grant to token endpoint, return responsereturn await client.RequestCustomGrantAsync("anonymous", "api2", payload); }Http 訪問示例:
POST /connect/tokengrant_type=anonymous& scope=api2& token=...& client_id=api1.client client_secret=secret參考資料:
Extension Grants
相關文章:
IdentityServer4(OAuth2.0服務)折騰筆記
IdentityServer4 實現 OpenID Connect 和 OAuth 2.0
IdentityServer4 使用OpenID Connect添加用戶身份驗證
IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架學習保護API
IdentityServer4 指定角色授權(Authorize(Roles="admin"))
IdentityServer4 SigningCredential(RSA 證書加密)
原文地址:http://www.cnblogs.com/xishuai/p/identityserver4-implement-custom-granttype.html
.NET社區新聞,深度好文,微信中搜索dotNET跨平臺或掃描二維碼關注
總結
以上是生活随笔為你收集整理的IdentityServer4 实现自定义 GrantType 授权模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET Standard@Xamari
- 下一篇: NET中解决KafKa多线程发送多主题的