【发布时间】:2021-09-07 19:20:01
【问题描述】:
问题说明:我遇到了这个问题,角色基础授权 ([Authorize(Roles = "Admin")]) 在 asp .net 5 中没有按预期工作,角色声明未添加到身份中。 p>
我搜索并尝试了许多解决方案,最后我能够弄清楚。所以我分享几个场景,以便它可以帮助某人。
【问题讨论】:
标签: asp.net-core .net-5 asp.net-authorization authorize asp.net5
问题说明:我遇到了这个问题,角色基础授权 ([Authorize(Roles = "Admin")]) 在 asp .net 5 中没有按预期工作,角色声明未添加到身份中。 p>
我搜索并尝试了许多解决方案,最后我能够弄清楚。所以我分享几个场景,以便它可以帮助某人。
【问题讨论】:
标签: asp.net-core .net-5 asp.net-authorization authorize asp.net5
如果您有一个继承自 IdentityUser 的自定义用户
例如:
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
您的服务配置正确,如下所示:
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>() /* Added role manager*/
.AddDefaultUI()
.AddEntityFrameworkStores<ApplicationDbContext>();
如果您没有为 UserPrincipal 使用自定义声明主体,那应该可以正常工作。
例如:
public class AppUserClaimsIdentityFactory : UserClaimsPrincipalFactory<ApplicationUser>
{
public AppUserClaimsIdentityFactory(
UserManager<ApplicationUser> userManager,
IOptions<IdentityOptions> optionsAccessor)
: base(userManager, optionsAccessor)
{
}
/* code implementation */
}
并使用 DI 注入它,如下所示:
services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, AppUserClaimsIdentityFactory>();
在这种情况下它不起作用,您需要为 UserClaimsPrincipalFactory 使用不同的构造函数重载并向其添加角色管理器。
更新您的自定义 UserClaimsIdentityFactory:
public class AppUserClaimsIdentityFactory :
UserClaimsPrincipalFactory<ApplicationUser,
IdentityRole>
/* Note: you can use your custom Role class or identity default */
{
public AppUserClaimsIdentityFactory(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager, /* Add role manager */
IOptions<IdentityOptions> optionsAccessor)
: base(userManager, roleManager /* send it to base constructor */, optionsAccessor)
{
}
/* code implementation */
}
您不必为自定义 UserClaimsPrincipalFactory 更改 Dependency Injection 容器中的任何内容。
一切都应该按预期正常工作。
【讨论】: