【问题标题】:Extend the ClaimsPrincipal and ClaimsIdentity classes in MVC-6扩展 MVC-6 中的 ClaimsPrincipal 和 ClaimsIdentity 类
【发布时间】:2015-05-25 15:59:22
【问题描述】:

这几天我一直在尝试解决这个问题,但必须(再次)求助于你们。

正如标题所说,我想实现我的自定义 ClaimsPrincipal 和 ClaimsIdentity,以便我可以将更多属性附加到我的 Identity-instance。

我之前在 MVC-5 中使用 Global.asax.cs 和继承的 BaseController 完成了这项工作。在 MVC-6 中,startup.cs 似乎是它的入口点,但我无法弄清楚。

这是我的两个课程:

public class BaseIdentity : ClaimsIdentity
{
    public Guid UserId { get; set; }
    public Guid OrgId { get; set; }
    public string OrgName { get; set; }

    public BaseIdentity()
    {
    }
}

还有..

public class BasePrincipal : ClaimsPrincipal
{
    private readonly BaseIdentity _identity;

    public BasePrincipal(BaseIdentity identity)
    {
        _identity = identity;
    }

    public new BaseIdentity Identity
    {
        get { return _identity; }
    }
}

在创建/检索 Auth cookie 时,如何使用这些类而不是默认类?

有一个名为 IApplicationBuilder.UseClaimsTransformation() 的方法,但找不到任何关于如何使用它的文档 - 如果它甚至适用于这种情况?

在这一点上非常感谢您的帮助! :)

顺便说一句:我想指出,当我第一次遇到这个挑战时,我在一周前问过a similar question。我得到了答案,但这是我真正必须解决的问题,以使我的网站可以在 MVC-6 上使用。

【问题讨论】:

  • 您目前如何创建身份验证 cookie?来自原始ClaimsIdentityClaim 属性应该在那里编码,然后您可以添加扩展方法来提取您的值;例如,GetUserId 已经可以通过 Identity 框架获得。
  • 嗯。您的意思是我应该将诸如 OrganizationId 之类的值存储为声明吗?我可能需要为此重新设计数据库,因为我在用户表中有一个外键作为对我当前设计中的组织的引用。但是,是的,也许可以使用声明代替 - 不过,我觉得慢一点?
  • 你不需要重新设计你的数据库;角色同样在数据库中标准化,但在ClaimsIdentity 中存储为Claims。
  • 嗯,好的。我过去没有使用过声明,所以我对这种方法有点陌生。但是,我是否理解正确,因为您会将 OrganizationId 保存为声明,然后使用 ClaimsPrincipal 类上的扩展方法来获取代码中的 OrganizationId?
  • 是的,我就是这个意思!作为参考,你可以在这里找到微软的GetUserIdgithub.com/aspnet/Identity/blob/…

标签: c# asp.net-core asp.net-core-mvc


【解决方案1】:

我使用扩展方法而不是继承来做到这一点。

public static class PrincipalExtensions
{
    public static string GetEmployeeNumber(this ClaimsPrincipal claimsPrincipal)
    {
        return claimsPrincipal.FindFirstValue("EmployeeNumber");
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    相关资源
    最近更新 更多