[Authorize(Roles="roleName")]
。然而,当我这样做时,即使我已经将指定的角色分配给用户,也会收到403错误。当我使用userManager.GetRolesAsync(user)
时,我发现该用户拥有该角色。当我使用[Authorize]选项进行请求时,如果用户已登录,则它按预期工作。我在当前用户的ClaimsPrincipal.Identity中检查了调试模式,并发现
RoleClaimType = "role"
。我查看了当前用户的声明并发现它没有使用“role”类型的声明。这就是[Authorize(Roles="...")]
的工作原理吗?它是查看声明吗?如果是这样,请问如何为用户的角色添加声明?这个应用程序中用户唯一的登录方式是通过Google账户。那么,如果他们由Google登录管理,我该怎么添加声明呢?下面是我的Startup.cs代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>()
.AddRoles<ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
services.AddAuthentication()
.AddGoogle(options =>
{
IConfigurationSection googleAuthNSection =
Configuration.GetSection("Authentication:Google");
options.ClientId = googleAuthNSection["ClientId"];
options.ClientSecret = googleAuthNSection["ClientSecret"];
})
.AddIdentityServerJwt();
services.AddControllersWithViews();
services.AddRazorPages();
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
if (!env.IsDevelopment())
{
app.UseSpaStaticFiles();
}
app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
这是控制器行为(Action)的一个示例:
[Authorize(Roles = "Admin")]
[HttpGet("userinformations")]
public async Task<UserInformations> GetCurrentUserInformations()
{
string strUserId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
ApplicationUser user = await userManager.FindByIdAsync(strUserId);
string[] roles = (await userManager.GetRolesAsync(user)).ToArray();
UserInformations userInfo = new UserInformations()
{
UserName = user.UserName,
FirstName = user.FirstName,
LastName = user.LastName,
Email = user.Email,
Organization = user.idDefaultOrganisation.HasValue ? user.DefaultOrganization.OrganizationName : "",
Claims = this.User.Claims.Select(c => $"{c.Type} : {c.Value}").ToArray(),
Roles = roles
};
return userInfo;
}
当我发出不带[Authorize(Roles = "Admin")]的请求时,我可以看到当前用户具有管理员角色,但当我添加此项时,我会收到403错误。
我做错了什么?我觉得我可能漏掉了一行或者类似的东西,因为在我找到的教程中,这一切似乎都很简单。
RolesAuthorizationRequirement
是如何实现的 https://github.com/dotnet/aspnetcore/blob/b56f84131af2e1ece61241a016e191f5f2fe3fc0/src/Security/Authorization/Core/src/RolesAuthorizationRequirement.cs然后你定义自己的策略并添加这个要求。查看此指南 https://geeklearning.io/create-your-own-authorization-requirements-in-asp-net-core/ - Michael ShterenbergRequireAssertion
解决方案。 - Michael Shterenberg[Authorize(Roles = "Admin")]
。这样,每当我的数据库中出现新角色时,我就不需要创建新的策略了。就像在身份验证期间,在数据库中检查用户角色以将它们添加到声明中一样。 - Rémy Huot