作者:Evilchrist | 来源:互联网 | 2023-10-11 18:16
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 claims = new List() { new Claim("role", GrantType) }; context.Result = new GrantValidationResult(GrantType, GrantType, claims);}
}
修改Client
配置:
new Client
{ClientId &#61; "client1",AllowedGrantTypes &#61; GrantTypes.List(GrantTypes.ResourceOwnerPassword.FirstOrDefault(), "anonymous"), AllowOfflineAccess &#61; true,AccessTokenLifetime &#61; 3600 * 6, SlidingRefreshTokenLifetime &#61; 1296000, ClientSecrets &#61;{ new Secret("123".Sha256())},AllowedScopes &#61; new List<string>{ "api2"}
}
DI 增加注入对象&#xff1a;
builder.AddExtensionGrantValidator();
调用示例代码&#xff1a;
public async Task AnonymousAsync(string userToken){ var payload &#61; new{token &#61; userToken}; var client &#61; new TokenClient(disco.TokenEndpoint, "client1", "123"); return await client.RequestCustomGrantAsync("anonymous", "api2", payload);
}
Http 访问示例&#xff1a;
POST /connect/tokengrant_type&#61;anonymous&
scope&#61;api2&
token&#61;...&
client_id&#61;api1.client
client_secret&#61;secret
参考资料&#xff1a;
相关文章&#xff1a;
IdentityServer4(OAuth2.0服务)折腾笔记
IdentityServer4 实现 OpenID Connect 和 OAuth 2.0
IdentityServer4 使用OpenID Connect添加用户身份验证
IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架学习保护API
IdentityServer4 指定角色授权&#xff08;Authorize(Roles&#61;"admin"))
IdentityServer4 SigningCredential&#xff08;RSA 证书加密&#xff09;
原文地址&#xff1a;http://www.cnblogs.com/xishuai/p/identityserver4-implement-custom-granttype.html
.NET社区新闻&#xff0c;深度好文&#xff0c;微信中搜索dotNET跨平台或扫描二维码关注