我是 .NET Core 的新手,我正在尝试在 .NET Core 3.1 项目中设置基于角色的授权。我相信我点击了每个在线讨论它的教程和线程。我的问题是它似乎很容易在教程上工作,但它对我不起作用。根据我发现的教程,我所要做的就是为数据库中的用户分配一个角色,然后[Authorize(Roles="roleName")]在控制器的操作之前使用。当我这样做时,对于具有指定角色的用户,我总是会收到 403 错误。当我使用 时userManager.GetRolesAsync(user),我看到用户具有角色。当我使用 [Authorize] 向此操作发出请求时,它会在用户登录时按预期工作。
我在调试模式下检查了当前用户的 ClaimsPrincipal.Identity,我发现RoleClaimType = "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");
}
});
}
这是控制器动作的示例
[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")] 的情况下向此操作发出请求时,我可以看到当前用户具有角色 Admin,但是当我添加它时,我收到 403 错误。
我究竟做错了什么?我觉得我在某处遗漏了一行或类似的东西,因为在我找到的教程中这一切似乎都很简单。