.Net Forms身份验证问题 - 401,即使cookie设置

时间:2014-06-17 22:18:15

标签: c# asp.net forms iis

我是C Sharp的新手,Windows窗体身份验证,IIS ....几乎所有东西。

我的问题:

-I'在布尔方法中验证登录/密码凭证

- 如果是,请执行以下操作:

//set and pass auth cookie
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, myUser, DateTime.Now, DateTime.Now.AddMinutes(30), isPersistent, String.Empty, FormsAuthentication.FormsCookiePath);
string encryptedCookie = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedCookie);
Response.Cookies.Add(cookie);
FormsAuthentication.SetAuthCookie(myUser,true);
FormsAuthentication.RedirectFromLoginPage(myUser,isPersistent);

根据我在firebug中看到的内容设置cookie。但是,当我重定向到上面的指定页面时,我给出了401 - 未经授权的通知。这是由我的代码中的错误引起的,还是因为用户/通行证在Windows域之外进行了身份验证?我应该在安全页面解密票证 - 我认为IIS / .Net做了什么?

包括我的Web.Config

<?xml version="1.0" encoding="UTF-8"?>
  <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
    <system.web>
      <customErrors mode="Off"/>
        <authentication mode="Forms"> 
          <forms defaultUrl="Secure/km.html" loginUrl="Public/login.html" name=".ASPXAUTH" requireSSL="true"> 
          </forms>
        </authentication>
   </system.web>
  </configuration>

我知道有很多类似的问题,但我已经完成了它们,似乎无法弄明白。欢迎任何帮助。感谢。

2 个答案:

答案 0 :(得分:1)

您是否已在global.asax.cs Application_AuthenticateRequestApplication_OnPostAuthenticateRequest中实施代码以获取FormsIdentity并将其转换为IPrincipal上的HttpContext.Current.User

    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        IPrincipal user = HttpContext.Current.User;
        if (user == null || !user.Identity.IsAuthenticated)
            return;

        var formsIdentity = HttpContext.Current.User.Identity as FormsIdentity;          
        var roles = formsIdentity.Ticket.UserData.Split(',');
        var gp = new GenericPrincipal(formsIdentity, roles);
        HttpContext.Current.User = gp;
    }

需要在web.config \ system.web中授权。

    <authorization>
        <deny users="?"/>
    </authorization>

答案 1 :(得分:0)

我想出了这个问题。我有名为.html的文件。在再次回顾教程之后,我将所有内容重命名为.aspx和low,并且看起来它按预期工作。

感谢提示小伙伴们,希望这有助于其他人。

这是我的最终代码

    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
    this.myUser,
    DateTime.Now,
    DateTime.Now.AddMinutes(30),
    this.isPersistent,
    String.Empty,  //Before I had this, Response.Redirect would return to Login
    FormsAuthentication.FormsCookiePath);

    // Encrypt the ticket.
    string encTicket = FormsAuthentication.Encrypt(ticket);

    // Create the Cookie
    HttpCookie myCookie = FormsAuthentication.GetAuthCookie(this.myUser, this.isPersistent);

   if(this.isPersistent)
      myCookie.Expires = DateTime.Now.AddDays(3);
   else
      myCookie.Expires = DateTime.Now.AddMinutes(30);

   myCookie.HttpOnly = true;
   myCookie.Path = FormsAuthentication.FormsCookiePath;
   Response.Cookies.Add(myCookie);
   Response.Redirect("/Secure/km.aspx");