2009-04-24 104 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]));