Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 761
Larsenal Avatar asked Apr 24 '09 19:04

Larsenal


2 Answers

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
like image 191
jellomonkey Avatar answered Nov 27 '22 20:11

jellomonkey


Looks like it may occur in the private method OnAuthenticate in System.Web.Security.FormsAuthenticationModule. The line is

 e.Context.SetPrincipalNoDemand(
      new GenericPrincipal(new FormsIdentity(ticket),
      new string[0]));
like image 40
Larsenal Avatar answered Nov 27 '22 20:11

Larsenal