ASP.NET核心自定义基于角色的授权(Custom User.IsInRole)?

And*_*rew 3 asp.net authorization .net-core coreclr

我通过一个名为Marten的库使用一个postgres数据库和一个.NET应用程序,我有一个IUserLoginStore管理检索用户及其角色的自定义.这似乎工作正常但我在设置授权时遇到问题.

我通过谷歌使用身份验证,它工作正常:

var info = await _signInManager.GetExternalLoginInfoAsync();
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
Run Code Online (Sandbox Code Playgroud)

此操作会抛出访问被拒绝的问题:

[HttpPost()]
[Authorize(Roles = "Admin")]
public JsonResult SubmitArticle([FromBody] ArticleInputModel input) {...}
Run Code Online (Sandbox Code Playgroud)

我已经挖了授权代码,问题似乎是默认ClaimsPrincipal代码:

public virtual bool IsInRole(string role)
{
  return false;
}
Run Code Online (Sandbox Code Playgroud)

我应该实现自己的版本ClaimsPrinciple并覆盖它IsInRole,如果我这样做,我怎么把它重新带回应用程序?

private static void ConfigureSecurity(IServiceCollection services)
{
    services.AddIdentity<User, Role>()
        .AddUserValidator<UserValidator>()
        .AddUserStore<MartenUserStore>()
        .AddRoleStore<MartenRoleStore>()
        .AddDefaultTokenProviders();
}
Run Code Online (Sandbox Code Playgroud)

And*_*rew 5

好吧,经过大量的挖掘后想出来,在我的情况下,MartenRoleStore实施IUserLoginStore它还需要实现IUserRoleStore哪些已经GetRolesAsyncIsInRoleAsync.(这非常重要,它必须与您用于.AddUserStore <>();)的完全相同的类.

这是我发现导致问题的代码:

https://github.com/aspnet/Identity/blob/master/src/Microsoft.AspNetCore.Identity/UserManager.cs#L258

这就是它的工作原理:

https://github.com/aspnet/Identity/blob/master/src/Microsoft.AspNetCore.Identity/UserClaimsPrincipalFactory.cs#L96