FormsAuthenticationTicket不存储UserData

时间:2012-09-28 15:00:36

标签: asp.net forms-authentication

我对.NET比较陌生,并试图弄清楚FormsAuthentication。我经历了一些不同的教程,每次遇到同样的问题。由于某种原因,UserData未存储在故障单中。当我在Global.aspx.cs中设置故障单时,UserName就在那里,但是UserData是一个空字符串,当指定为1时,Version设置为2.另一个奇怪的是每个经过身份验证的用户都被允许当web.config指定只有管理员可以。

时访问Admin_Content文件夹中的页面

的Login.aspx

UserFull user = ManageUsers.login(loginTemplate.UserName, loginTemplate.Password);
if (user != null)
{
    string[] roles = { user.role };

    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
        1,
        userName,
        DateTime.Now,
        DateTime.Now.AddDays(30),
        true,
        roles[0],
        FormsAuthentication.FormsCookiePath
    );

    string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
    FormsAuthentication.SetAuthCookie(encryptedTicket, true);

    Response.Redirect("Admin_Content/Admin.aspx");
 }

Global.aspx.cs Application_AuthenticateRequest

if (HttpContext.Current.User != null)
{
    if (HttpContext.Current.User.Identity.IsAuthenticated)
    {
        if (HttpContext.Current.User.Identity is FormsIdentity)
        {
            FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
            FormsAuthenticationTicket ticket = (id.Ticket);
            if (!string.IsNullOrEmpty(ticket.UserData))
            {
                string userData = ticket.UserData;
                string[] roles = userData.Split(',');
                HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
            }
        }
    }
}

主要web.config

<configuration>
<system.web>
  <compilation debug="true" targetFramework="4.0" />
  <roleManager enabled="true"></roleManager>
  <authentication mode="Forms">
    <forms name="AOTMP_Demo" loginUrl="Login.aspx"
    protection="All" path="/" cookieless="UseCookies"/>
  </authentication>
  <authorization>
    <allow users="*"/>
  </authorization>
</system.web>
<configuration>

Admin_Content文件夹的web.config

<configuration>  
  <system.web>
    <authorization>
      <allow roles="Administrator"/>
      <deny users="?"/>
    </authorization>
  </system.web>
</configuration>

2 个答案:

答案 0 :(得分:1)

你不应该这样做......因为它会创建一个新的授权凭证。

FormsAuthentication.SetAuthCookie();

而是明确设置cookie

var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.Expires = authTicket.Expiration;
Request.Cookies.Add(cookie);

然后它将在global.asax

中提供
var userData = ((FormsIdentity)HttpContext.Current.User.Identity).Ticket.UserData;

答案 1 :(得分:0)

尝试更改

string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
FormsAuthentication.SetAuthCookie(encryptedTicket, true);

HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);

我相信FormsAuthentication.SetAuthCookie已在内部调用FormsAuthentication.Encrypt,因此您可能会收到格式错误的Cookie。