5

我有

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 中的用户名何时被设置为我当前用户身份中的名称?

4

2 回答 2

4

用户名只是 IPrinciple 用户对象的一个​​属性,并且该对象设置在标准 ASP.NET HTTPModules 之一中,在您的情况下,可能是 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
于 2009-04-24T20:24:46.750 回答
2

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

 e.Context.SetPrincipalNoDemand(
      new GenericPrincipal(new FormsIdentity(ticket),
      new string[0]));
于 2009-04-24T19:59:01.490 回答