Web.HttpContext.Current.User.Identity.Name来自哪里?

Lar*_*nal 5 asp.net forms-authentication httpcontext roleprovider

我有

FormsAuthentication.SetAuthCookie("someName", True)
Run Code Online (Sandbox Code Playgroud)

作为我的自定义登录序列的一部分.后来,我有一些页面只允许一个特定的角色:

<location path="myPage.aspx">
    <system.web>
        <authorization>
            <allow roles="SomeRole"/>
            <deny users="*"/>
        </authorization>
    </system.web>
</location>
Run Code Online (Sandbox Code Playgroud)

据我所知,这会调用我的角色提供程序的GetRolesForUser实现.它似乎从Web.HttpContext.Current.User.Identity.Name获取用户名参数.

我的问题是...... 来自auth cookie的用户名何时被设置为我当前用户身份中的名称?

jel*_*key 4

用户名只是 IPrinciple 用户对象的一个​​属性,该对象是在标准 ASP.NET HTTPModule 之一中设置的,在您的情况下可能是 System.Web.Security.FormsAuthenticationModule 作为 OnAuthenticate 方法的一部分。

如果您想知道如何更改此信息,例如设置不同的用户名或身份,您将需要创建一个 global.asax 或覆盖 Application_AuthenticateRequest 的自定义 HTTPModule。这是一个例子:

Public Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim cookieName As String = FormsAuthentication.FormsCookieName
    Dim authCookie As HttpCookie = HttpContext.Current.Request.Cookies(FormsAuthentication.FormsCookieName)

    If Not IsNothing(authCookie) Then
        Dim authTicket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(authCookie.Value)
        If IsNothing(authTicket) OrElse authTicket.Expired Then
            HttpContext.Current.Response.Redirect(FormsAuthentication.LoginUrl)
        Else
            Dim id As New FormsIdentity(authTicket)

            Dim newUser As New YourCustomUserType(id.Name)
            HttpContext.Current.User = newUser
        End If
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)