【问题标题】:ASP.NET Core Custom Role Based Authorization (Custom User.IsInRole)?ASP.NET Core 自定义基于角色的授权(自定义 User.IsInRole)?
【发布时间】:2017-04-06 21:51:14
【问题描述】:

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

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

var info = await _signInManager.GetExternalLoginInfoAsync();
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);

此操作引发访问被拒绝问题:

[HttpPost()]
[Authorize(Roles = "Admin")]
public JsonResult SubmitArticle([FromBody] ArticleInputModel input) {...}

我已经深入研究了授权代码,问题似乎与默认的ClaimsPrincipal 代码有关:

public virtual bool IsInRole(string role)
{
  return false;
}

我是否应该实现我自己的ClaimsPrinciple 版本并覆盖IsInRole,如果我这样做了如何将它恢复到应用程序中?

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

【问题讨论】:

标签: asp.net authorization .net-core coreclr


【解决方案1】:

好吧,经过大量挖掘后发现,在我的情况下,MartenRoleStore 正在实现IUserLoginStore,它还需要实现IUserRoleStore,它具有GetRolesAsync 和IsInRoleAsync。 (这非常重要,它必须与您用于 .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

【讨论】:

猜你喜欢
  • 2021-11-26
  • 2014-10-22
  • 2021-03-17
  • 2020-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多