Where does Web.HttpContext.Current.User.Identity.Name come from?

Larsenal picture Larsenal · Apr 24, 2009 · Viewed 10k times · Source

I have

FormsAuthentication.SetAuthCookie("someName", True)

as part of my custom login sequence. Later, I have some page only allowing a specific role:

<location path="myPage.aspx">
    <system.web>
        <authorization>
            <allow roles="SomeRole"/>
            <deny users="*"/>
        </authorization>
    </system.web>
</location>

As far as I can tell, that makes a call to my role provider's implementation of GetRolesForUser. It appears to get the username parameter from Web.HttpContext.Current.User.Identity.Name.

My question is.... when does the username from the auth cookie get set as the Name in my current user identity?

Answer

jellomonkey picture jellomonkey · Apr 24, 2009

The username is just a property of the IPrinciple user object and that object is set in one of the standard ASP.NET HTTPModules, in your case probably System.Web.Security.FormsAuthenticationModule as part of the OnAuthenticate method.

If what you want to know is how to change this information, such as setting a different username or identity, you will want to look at creating a global.asax or a custom HTTPModule which overrides the Application_AuthenticateRequest. Here is an example:

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