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!=""){
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(),
creds
);
return Ok(new {token = new JwtSecurityTokenHandler().WriteToken(token)});
}
return BadRequest();
}

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

39-Role以及Claims授权-LMLPHP

基于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
};
05-26 08:00