我在使用 JWT 生成的 token 中有以下有用的负载
{ “子”:“flamelsoft@gmail.com”, “jti”:“0bca1034-f3ce-4f72-bd91-65c1a61924c4”, "http://schemas.microsoft.com/ws/2008/06/identity/claims/role ": "管理员", “exp”:1509480891, “iss”:“http://localhost:40528”, “aud”:“http://localhost:40528”
用这个代码 启动.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();
}
AccountController.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 });
}
}}
问题是角色的验证不起作用,请求到达 Controller 并在 header 中返回代码 200,但从未进入类。 当我删除 [Authorize (Roles = "Administrator")] 时,它会正确输入我的代码。 有什么东西定义不好吗?或者通过角色定义授权的替代方案是什么。
最佳答案
长话短说
如原始问题的评论中所述,更改:
[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
}
解决了这个问题。
Bearer
是 default authentication scheme name在 ASP.NET Core 中使用 JWT 承载身份验证时。
但为什么我们需要在 [Authorize]
属性上指定 AuthenticationSchemes
属性?
这是因为配置身份验证方案并不意味着它们将在每个 HTTP 请求上运行。如果匿名用户可以访问特定操作,为什么还要费心从 cookie 或 token 中提取用户信息? MVC 对此很聪明,只会在需要时运行身份验证处理程序,也就是说,在以某种方式受到保护的请求期间。
在我们的例子中,MVC 发现了 [Authorize]
属性,因此知道它必须运行身份验证和授权以确定请求是否被授权。诀窍在于它只会运行 authentication schemes handlers。已指定。在这里,我们没有,所以没有执行身份验证,这意味着授权失败,因为请求被认为是匿名的。
将身份验证方案添加到属性指示 MVC 运行该处理程序,该处理程序从 HTTP 请求中的 token 中提取用户信息,这导致 Administrator
角色被发现,并且请求被允许.
附带说明一下,还有另一种方法可以实现此目的,无需使用 [Authorize]
属性的 AuthenticationSchemes
属性。
假设您的应用程序只配置了一个身份验证方案,必须在每个 [Authorize]
属性上指定 AuthenticationSchemes
属性会很痛苦。
使用 ASP.NET Core,您可以配置默认 身份验证方案。这样做意味着关联的处理程序将为每个 HTTP 请求运行,无论资源是否 protected 。
此设置分两部分完成:
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 评估请求是否被授权时,身份验证已经发生,因此不为 [Authorize] 的
属性不会有问题。AuthenticationSchemes
属性指定任何值]
该过程的授权部分仍将运行并检查经过身份验证的用户是否属于 Administrator
组。
关于c# - .Net Core 2 JWT,Angular 2 通过角色授权不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47043799/