如何在ASP.NET MVC中实现自定义Principal和Identity?

Ken*_*ina 16 identity forms-authentication principal asp.net-mvc-2

我想在经过身份验证的用户中存储额外的信息,以便我可以轻松访问它(例如User.Identity.Id),而不仅仅是名称,因为我计划让它具有非唯一性.

到目前为止,我已经收集到了我应该寻求实现自定义Principal和/或Identity,但我不确定如何去实现它.我一直在寻找有关此事的文档和教程,但我在不同的地方找到了相关的东西,我发现它有点令人困惑.

我已经看到了如何将自定义信息添加到用户数据属性中的身份验证cookie,但我希望获得单元测试的依赖注入的好处,我可以使用主体和身份.

如果我想实现自己的Principal或Identity,我需要考虑哪些确切的步骤?

在这种情况下我能做的最简单的事情是什么(只需添加ID并保留所有默认值)?"默认值"将包括默认提供者(成员资格,角色等).

我已经看到了另一个问题,但我很欣赏不会在两者之间留下任何漏洞的答案,例如示例中AuthenticateRequest事件中的角色魔术字符串.相反,我需要知道如何将默认SqlRoleProvider中的角色添加到当前用户:何时何地执行此操作,以及是否需要执行任何其他操作以将新类与其他默认提供程序连接.

能够转到示例ASP.NET MVC 2应用程序(例如,来自visual studio 2010模板),进行编辑并使其工作是非常棒的.


编辑:我已经编辑了这个问题,以便更好地表明我在这里已经失去了很多,所以我无法用太高的答案来做.

PS:在我看来,在身份而不是校长中使用ID会更有意义,尽管我在某种程度上已经说过这个.

Set*_*eno 20

之前已经提出并回答过这个问题: ASP.NET MVC - 设置自定义IIdentity或IPrincipal

但总结一下......

使用您要存储的其他属性来创建自定义主体类:

Public Class CustomPrincipal
    Inherits System.Security.Principal.GenericPrincipal

    Private _eyeColor As String
    Public ReadOnly Property EyeColor As String
        Get
            Return _eyeColor
        End Get
    End Property

    Public Sub New(id As System.Security.Principal.IIdentity, roles As String(), eyeColor As String)
        MyBase.New(id, roles)
        _eyeColor = eyeColor            
    End Sub

End Class
Run Code Online (Sandbox Code Playgroud)

修改global.asax Global.Application_AuthenticateRequest以使用您的自定义主体:

Protected Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As System.EventArgs)
    ...
    Dim roles() As String = {"examplerole"}         
    Context.User = new CustomPrincipal(Context.User.Identity, roles, "green")
End Sub
Run Code Online (Sandbox Code Playgroud)

然后,当您想要引用其中一个属性时,代码中的其他位置执行以下操作:

CType(My.User.CurrentPrincipal, CustomPrincipal).EyeColor
Run Code Online (Sandbox Code Playgroud)