2 回答

TA貢獻(xiàn)1803條經(jīng)驗 獲得超6個贊
該Authorize
屬性本身僅用于指定您在特定頁面或控制器上所需的授權(quán)類型。此屬性旨在與身份框架一起使用,并且可以包括角色、策略和身份驗證方案。
您需要在 Identity 框架和您的數(shù)據(jù)庫之間建立一座橋梁,這可以通過自定義UserStore
and來完成RoleStore
,這在此頁面上有詳細(xì)描述。
總結(jié)一個相當(dāng)復(fù)雜的過程:
該
Authorize
屬性指示瀏覽器對您的用戶進(jìn)行身份驗證您的用戶被重定向到身份驗證頁面
如果成功,您將獲得一個
ClaimsPrincipal
實例,然后您需要通過自定義映射到您的數(shù)據(jù)庫用戶UserStore
然后可以根據(jù)數(shù)據(jù)庫角色檢查您的用戶
這是所有這些實際操作的簡短示例(不完全完整,因為它的代碼太多了)。
啟動.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貢獻(xiàn)1856條經(jīng)驗 獲得超11個贊
.Net Core -> 如果要使用基于策略的方法,則必須在 startup.cs 的 ConfigureServices 方法中定義策略定義
例子:
services.AddAuthorization(options =>
{
options.AddPolicy("UserPolicy", policy => policy.RequireRole("USER"));
});
然后您可以在控制器或操作方法中應(yīng)用如下策略。
授權(quán)(策略 = “用戶策略”)
- 2 回答
- 0 關(guān)注
- 140 瀏覽
添加回答
舉報