39-Role以及Claims授权

Posted qinzb

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了39-Role以及Claims授权相关的知识,希望对你有一定的参考价值。

asp.net core多鼓励使用claims授权

1-使用role授权

在类或方法上贴上Roles,这样就知道有user的角色才可以访问

 [Authorize(Roles="user")]
    public class ValuesController : ControllerBase

 

在登陆时给用户分配对应的角色  new Claim(ClaimTypes.Role,"admin")

 public IActionResult Token(LoginViewModel loginViewModel){
           if(ModelState.IsValid) {
              if(loginViewModel.User!="qinzb" && loginViewModel.Password!="123"){
                  return BadRequest();
              }

              var claims = new Claim[]{
                    new Claim(ClaimTypes.Name,"qinzb"),
                    new Claim(ClaimTypes.Role,"admin")
               };
              
              var key = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey
              (System.Text.Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));

              var creds = new Microsoft.IdentityModel.Tokens.SigningCredentials
              (key, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256);

              var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(
                  _jwtSettings.Issure,
                _jwtSettings.Audience,
                claims,
                null,
                DateTime.Now.AddMinutes(30),
                creds
              );
              return Ok(new {token = new JwtSecurityTokenHandler().WriteToken(token)});
           }
           return BadRequest();
       }

 

如果没有访问方法的对应角色,则返回如下提示

技术分享图片

 

基于claims授权,只需要多加

services.AddAuthorization(options=>{
                options.AddPolicy("SuperAdminOnly",policy=>policy.RequireClaim("SuperAdminOnly"));
            });

 完整代码

  public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
            var jwtSetting =  new JwtSettings();
            Configuration.Bind("JwtSettings",jwtSetting);

            services.AddAuthentication(options=>{
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(jwtOption=>{
                jwtOption.TokenValidationParameters=new Microsoft.IdentityModel.Tokens.TokenValidationParameters{
                    ValidIssuer = jwtSetting.Issure,
                    ValidAudience = jwtSetting.Audience,
                    IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(
                        System.Text.Encoding.UTF8.GetBytes(jwtSetting.SecretKey)
                    )
                };
                // jwtOption.SecurityTokenValidators.Clear();
                // jwtOption.SecurityTokenValidators.Add(new MyTokenValidator());
                // jwtOption.Events = new JwtBearerEvents(){
                //     OnMessageReceived = Context=>{
                //         var token = Context.Request.Headers["token"];
                //         Context.Token = token;
                //         return Task.CompletedTask;
                //     }
                // };

            });

            services.AddAuthorization(options=>{
                options.AddPolicy("SuperAdminOnly",policy=>policy.RequireClaim("SuperAdminOnly"));
            });
        }

2-在需要的类上启用claims, Policy表示只用SuperAdminOnly的才能访问

   [Authorize(Policy="SuperAdminOnly")]
    public class ValuesController : ControllerBase

 

3-在登陆时给对应的类增加policy,这样可以访问带有[Authorize(Policy="SuperAdminOnly")

   var claims = new Claim[]{
                    new Claim(ClaimTypes.Name,"qinzb"),
                    new Claim(ClaimTypes.Role,"admin"), //基于角色
                    new Claim("SuperAdminOnly","true") //基于policy
               };

 



以上是关于39-Role以及Claims授权的主要内容,如果未能解决你的问题,请参考以下文章

IdentityServer4-从数据库获取User登录并对Claims授权验证

认证授权方案之授权初识

基于IdentityServer4的声明的授权

Claims-based认证解析

新功能项目授权

Security » Authorization » 基于声明的授权