温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何进行IdentityServer4 指定角色授权

发布时间:2021-12-30 10:02:11 阅读:216 作者:柒染 栏目:大数据
亿速云云数据库,读写分离,安全稳定,弹性扩容,低至0.3元/天!! 点击查看>>

本篇文章为大家展示了如何进行IdentityServer4 指定角色授权,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

1. 业务场景

IdentityServer4 授权配置Client中的AllowedScopes,设置的是具体的 API 站点名字,也就是使用方设置的ApiName,示例代码:

//授权中心配置new Client{    ClientId = "client_id_1",    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,    AllowOfflineAccess = true,    AccessTokenLifetime = 3600 * 6, //6小时    SlidingRefreshTokenLifetime = 1296000, //15天    ClientSecrets =    {        new Secret("secret".Sha256())    },    AllowedScopes =     {        "api_name1"    },}//API 服务配置app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions{    Authority = $"http://localhost:5000",    ApiName = "api_name1",    RequireHttpsMetadata = false});

上面两个api_name1配置要一致,问题来了,因为授权中心的scope配置是整个 API 服务,如果我们存在多个Client配置,比如一个前台和后台,然后都需要访问api_name1,就会出现一些问题。

比如,api_name1服务中的一个接口服务配置代码:

[Authorize()]
[Route("api/values")]
[HttpGet]public IActionResult Get(){    return Ok();
}

Authorize()的配置,说明api/values接口需要授权后访问,如果授权中心配置了两个Client(前台和后台),并且scope都包含了api_name1,现在就会出现两种情况:

  1. 前台Client和后台Client,都需要授权后访问api/values接口:没有问题。

  2. 前台Client不需要授权后访问,后台Client需要授权后访问:有问题,前台Client没办法访问了,因为api/values接口设置了Authorize()

其实,说明白些,就是该如何让 API 服务指定Client授权访问?比如:[Authorize(ClientId = 'client_id_1')]

2. 解决方案

没有[Authorize(ClientId = 'client_id_1')]这种解决方式,不过可以使用[Authorize(Roles = 'admin')]

授权中心的ResourceOwnerPasswordValidator代码,修改如下:

public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator{    private readonly IUserService _userService;    public ResourceOwnerPasswordValidator(IUserService userService)    {        _userService = userService;    }    public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)    {        var user = await _userService.Login(context.UserName, context.Password);        if (user != null)        {            var claims = new List<Claim>() { new Claim("role", "admin") }; //根据 user 对象,设置不同的 role            context.Result = new GrantValidationResult(user.UserId.ToString(), OidcConstants.AuthenticationMethods.Password, claims);        }    }}

授权中心的startup配置,修改如下

var builder = services.AddIdentityServer();builder.AddTemporarySigningCredential()        //.AddInMemoryIdentityResources(Config.GetIdentityResources())        .AddInMemoryApiResources(new List<ApiResource>        {            new ApiResource("api_name1", "api1"){ UserClaims = new List<string> {"role"}}, //增加 role claim            new ApiResource("api_name2", "api2"){ UserClaims = new List<string> {"role"}}        })        .AddInMemoryClients(Config.GetClients());

API 服务接口,只需要配置如下:

[Authorize()][Route("api/values")][HttpGet]public IActionResult Get(){    return Ok();}[Authorize(Roles = "admin")][Route("api/values2")][HttpGet]public IActionResult Get2(){    return Ok();}[Authorize(Roles = "admin,normal")][Route("api/values3")][HttpGet]public IActionResult Get3(){    return Ok();}

需要注意的是,api/values接口虽然没有设置具体的Roles,但每个Role都可以访问。

上述内容就是如何进行IdentityServer4 指定角色授权,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

原文链接:https://my.oschina.net/u/3772973/blog/4615488

AI

开发者交流群×