2 回答
TA贡献1803条经验 获得超6个赞
该Authorize
属性本身仅用于指定您在特定页面或控制器上所需的授权类型。此属性旨在与身份框架一起使用,并且可以包括角色、策略和身份验证方案。
您需要在 Identity 框架和您的数据库之间建立一座桥梁,这可以通过自定义UserStore
and来完成RoleStore
,这在此页面上有详细描述。
总结一个相当复杂的过程:
该
Authorize
属性指示浏览器对您的用户进行身份验证您的用户被重定向到身份验证页面
如果成功,您将获得一个
ClaimsPrincipal
实例,然后您需要通过自定义映射到您的数据库用户UserStore
然后可以根据数据库角色检查您的用户
这是所有这些实际操作的简短示例(不完全完整,因为它的代码太多了)。
启动.cs
// This class is what allows you to use [Authorize(Roles="Role")] and check the roles with the custom logic implemented in the user store (by default, roles are checked against the ClaimsPrincipal roles claims)
public class CustomRoleChecker : AuthorizationHandler<RolesAuthorizationRequirement>
{
private readonly UserManager<User> _userManager;
public CustomRoleChecker(UserManager<User> userManager)
{
_userManager = userManager;
}
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, RolesAuthorizationRequirement requirement)
{
var user = await _userManager.GetUserAsync(context.User);
// for simplicity, I use only one role at a time in the attribute
var singleRole = requirement.AllowedRoles.Single();
if (await _userManager.IsInRoleAsync(user, singleRole))
context.Succeed(requirement);
}
}
public void ConfigureServices(IServiceCollection services)
{
services
.AddIdentity<User, Role>()
.AddUserStore<MyUserStore>()
.AddRoleStore<MyRoleStore>();
// custom role checks, to check the roles in DB
services.AddScoped<IAuthorizationHandler, CustomRoleChecker>();
}
您的 EF Core 实体在哪里User,是哪里。Role
我的用户商店
public class MyUserStore : IUserStore<User>, IUserRoleStore<User>, IQueryableUserStore<User>
{
private Context _db;
private RoleManager<Role> _roleManager;
...
public async Task<User> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken)
{
// bridge your ClaimsPrincipal to your DB users
var user = db.Users.SingleOrDefault(_ => _.Email.ToUpper() == normalizedUserName);
return await Task.FromResult(user);
}
...
public async Task<bool> IsInRoleAsync(User user, string roleName, CancellationToken cancellationToken)
{
if (roleName == null)
return true;
// your custom logic to check role in DB
var result = user.Roles.Any(_ => _.RoleName == roleName);
return await Task.FromResult(result);
}
TA贡献1856条经验 获得超11个赞
.Net Core -> 如果要使用基于策略的方法,则必须在 startup.cs 的 ConfigureServices 方法中定义策略定义
例子:
services.AddAuthorization(options =>
{
options.AddPolicy("UserPolicy", policy => policy.RequireRole("USER"));
});
然后您可以在控制器或操作方法中应用如下策略。
授权(策略 = “用户策略”)
- 2 回答
- 0 关注
- 121 浏览
添加回答
举报