[英].Net Core 2 JWT, Angular 2 Authorization through roles does not work
我在用 JWT 生成的令牌中有以下有用的负载
{ "sub": "flamelsoft@gmail.com", "jti": "0bca1034-f3ce-4f72-bd91-65c1a61924c4", " http://schemas.microsoft.com/ws/2008/06/identity/claims/角色":"管理员","exp":1509480891,"iss":" http://localhost:40528 ","aud":" http://localhost:40528 "}
使用此代码 Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DBContextSCM>(options =>
options.UseMySql(Configuration.GetConnectionString("DefaultConnection"), b =>
b.MigrationsAssembly("FlamelsoftSCM")));
services.AddIdentity<User, Role>()
.AddEntityFrameworkStores<DBContextSCM>()
.AddDefaultTokenProviders();
services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
services.AddAuthentication()
.AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;
cfg.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = Configuration["Tokens:Issuer"],
ValidAudience = Configuration["Tokens:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
};
});
services.AddMvc();
}
账户控制器.cs
[HttpPost]
[Authorize(Roles="Administrator")]
public async Task<IActionResult> Register([FromBody]RegisterModel model)
{
try
{
var user = new User { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var role = await _roleManager.FindByIdAsync(model.Role);
result = await _userManager.AddToRoleAsync(user, role.Name);
if (result.Succeeded)
return View(model);
}
return BadRequest($"Error: Could not create user");
}
catch (Exception ex)
{
return BadRequest($"Error: {ex.Message}");
}
}
用户服务.ts
export class UserService {
constructor(private http: Http, private config: AppConfig, private currentUser: User) { }
create(user: User) {
return this.http.post(this.config.apiUrl + 'Account/Register', user, this.jwt());
}
private jwt() {
const userJson = localStorage.getItem('currentUser');
this.currentUser = userJson !== null ? JSON.parse(userJson) : new User();
if (this.currentUser && this.currentUser.token) {
let headers = new Headers({ 'Authorization': 'Bearer ' + this.currentUser.token });
return new RequestOptions({ headers: headers });
}
}}
问题是角色的验证不起作用,请求到达控制器并在header中返回代码200,但从未进入类。 当我删除 [Authorize (Roles = "Administrator")] 时,它会正确输入我的代码。 有什么不好的定义吗? 或者通过角色定义授权的替代方法是什么。
TL; DR
如原始问题的评论中所述,更改:
[HttpPost]
[Authorize(Roles = "Administrator")]
public async Task<IActionResult> Register([FromBody]RegisterModel model)
{
// Code
}
至
[HttpPost]
[Authorize(AuthenticationSchemes = "Bearer", Roles = "Administrator")]
public async Task<IActionResult> Register([FromBody]RegisterModel model)
{
// Code
}
解决了这个问题。
在ASP.NET Core中使用JWT承载认证时, Bearer
是默认的认证方案名称 。
但是为什么我们需要在[Authorize]
属性上指定AuthenticationSchemes
属性?
这是因为配置身份验证方案并不意味着它们将在每个HTTP请求上运行。 如果匿名用户可以访问特定操作,为什么还要从cookie或令牌中提取用户信息呢? MVC对此非常聪明,并且只在需要时运行身份验证处理程序,即在以某种方式受到保护的请求期间运行。
在我们的例子中,MVC发现[Authorize]
属性,因此知道它必须运行身份验证和授权来确定请求是否被授权。 诀窍在于它只运行已指定的身份验证方案处理程序 。 在这里,我们没有,所以没有执行身份验证,这意味着授权失败,因为请求被认为是匿名的。
将身份验证方案添加到属性指示MVC以运行该处理程序,该处理程序从HTTP请求中的令牌中提取用户信息,这导致发现Administrator
角色,并且允许该请求。
作为旁注,还有另一种方法可以实现这一点,而无需使用[Authorize]
属性的AuthenticationSchemes
属性。
想象一下,您的应用程序只配置了一个身份验证方案,必须在每个[Authorize]
属性上指定AuthenticationSchemes
属性是一件痛苦的事。
使用ASP.NET Core,您可以配置默认的身份验证方案。 这样做意味着将为每个HTTP请求运行关联的处理程序,无论资源是否受到保护。
设置它分为两部分:
public class Startup
{
public void ConfiguresServices(IServiceCollection services)
{
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme /* this sets the default authentication scheme */)
.AddJwtBearer(options =>
{
// Configure options here
});
}
public void Configure(IApplicationBuilder app)
{
// This inserts the middleware that will execute the
// default authentication scheme handler on every request
app.UseAuthentication();
app.UseMvc();
}
}
这样做意味着在MVC评估请求是否被授权时,已经进行了AuthenticationSchemes
,因此不指定[Authorize]
属性的AuthenticationSchemes
属性的任何值都不会有问题。
进程的授权部分仍将运行,并检查经过身份验证的用户是否属于Administrator
组。
我知道这个问题已经有了答案,但这里遗漏了一些重要的东西。 您需要确保您确实为登录用户设置了声明。 就我而言,我使用的是 JWT 身份验证,因此这一步非常重要:
var claims = new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, user.UserName) });
var roles = await _userManager.GetRolesAsync(user);
if (roles.Count > 0)
{
foreach (var role in roles) { claims.AddClaim(new Claim(ClaimTypes.Role, role)); }
}
var token = new JwtSecurityToken(
issuer: _configuration["JWT:Issuer"],
audience: _configuration["JWT:Audience"],
expires: DateTime.UtcNow.AddMinutes(15),
signingCredentials: signingCredentials,
claims: claims.Claims);
我正在努力弄清楚为什么HttpContext.User
没有包含我期望缩小[Authroization(Roles="Admin")]
问题的范围。 事实证明,如果您使用JWT身份验证,您需要记住将Claims[]
设置为身份。 也许这是通过其他dotnet
方式自动完成的,但jwt
似乎要求您手动设置。
在我为用户设置声明后, [Authorize(Roles = "Whatever")]
按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.