在ASP.NET Core 2.2中,如果在Controller上使用了[Authorize(Roles="role1, role2")]属性,而该属性在运行时没有起作用,可以按照以下步骤解决:
services.AddAuthentication("CookieAuth")
.AddCookie("CookieAuth", config =>
{
config.Cookie.Name = "YourCookieName";
config.LoginPath = "/Account/Login";
});
services.AddAuthorization(config =>
{
config.AddPolicy("Admin", policy =>
{
policy.RequireRole("Admin");
});
});
app.UseAuthentication();
app.UseAuthorization();
var claims = new List
{
new Claim(ClaimTypes.Name, "John"),
new Claim(ClaimTypes.Email, "john@example.com"),
new Claim(ClaimTypes.Role, "Admin") // 分配"Admin"角色
};
var identity = new ClaimsIdentity(claims, "CookieAuth");
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync("CookieAuth", principal);
如果按照以上步骤操作后,[Authorize(Roles="role1, role2")]仍然不起作用,可以尝试以下额外的解决方法:
[Authorize(Roles="role1,role2")]
确保角色名称的大小写匹配。有时,角色名称的大小写可能会导致授权失败。
如果在使用自定义角色提供程序,确保角色提供程序正确设置和配置。
通过以上步骤,应该能够解决ASP.NET Core 2.2中[Authorize(Roles="role1, role2")]不起作用的问题。