2009-04-24 151 views
5

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

FormsAuthentication.SetAuthCookie("someName", True) 

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

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

至于我可以告诉大家,这使得我的角色提供者实现GetRolesForUser的呼叫。它似乎从Web.HttpContext.Current.User.Identity.Name获得用户名参数。

我的问题是...... 什么时候auth cookie的用户名被设置为我当前用户标识中的Name?

回答

3

用户名是只是一个IPrinciple用户对象的属性和对象被设置在标准ASP.NET的HttpModules的一个,你的情况可能System.Web.Security.FormsAuthenticationModule作为的一部分OnAuthenticate方法。

如果你想知道如何改变这些信息,比如设置一个不同的用户名或者标识,你需要考虑创建一个global.asax或者一个自定义的HTTPModule来覆盖Application_AuthenticateRequest。这里是一个例子:

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 
2

看起来好像它可能发生在System.Web.Security.FormsAuthenticationModule的私有方法OnAuthenticate中。该生产线是

e.Context.SetPrincipalNoDemand(
     new GenericPrincipal(new FormsIdentity(ticket), 
     new string[0]));