Sco*_*ttG 3 c# authorization asp.net-core asp.net-core-2.0
我有一系列网页,并且在自定义数据库表中定义了对这些网页的授权。例如,我有一个名为“超级用户”的角色,该角色被允许访问某些网页。我有分配给该角色的用户。
我不明白如何将 Authorize 属性放在控制器上并传入页面名称(视图),然后从我的数据库中读取某种类型的自定义处理程序,以查看用户是否在具有权限的组中. 我一直在这里阅读基于策略的授权:https : //docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore - 2.2并试图理解它我的情况。
我是否在基于策略的授权的正确轨道上,或者在允许用户访问页面之前是否有另一种方法来进行数据库检查权限?
该Authorize属性本身仅用于指定您在特定页面或控制器上所需的授权类型。此属性旨在与身份框架一起使用,并且可以包括角色、策略和身份验证方案。
您需要的是在 Identity 框架和您的数据库之间创建一座桥梁,这可以通过自定义UserStore和来完成RoleStore,这在本页中有详细描述。
总结一个相当复杂的过程:
Authorize属性指示浏览器对您的用户进行身份验证ClaimsPrincipal实例,然后您需要通过自定义映射到您的数据库用户UserStore这是所有这些操作的简短示例(不完全完整,因为代码太多)。
启动文件
// 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>();
}
Run Code Online (Sandbox Code Playgroud)
您的 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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3740 次 |
| 最近记录: |