IE11下Forms身份认证无法保存Cookie的问题

简介:

ASP.NET中使用Forms身份认证常见的做法如下:

1. 网站根目录下的Web.config添加authentication节点

<authentication mode="Forms">
  <forms name="MyAuth" loginUrl="manager/Login.aspx" defaultUrl="manager/default.aspx" protection="All" timeout="60" />
</authentication>

2. 在manager子目录下添加Web.config文件并加入下面的内容:

复制代码
<?xml version="1.0"?>
<configuration>
    <system.web>
      <authorization>
        <allow roles="Admin" />
        <deny users="*" />
      </authorization>
    </system.web>
</configuration>
复制代码

  这样,用户在没有Forms认证的情况下访问manager子目录下的任何页面均会自动跳转到manager/Login.aspx页面。如果认证成功,则会默认回到manager/default.aspx页面。认证有效期为60分钟。

3. 添加认证代码。登录按钮中添加下面的代码:

复制代码
if (!snCheckCode.CheckSN(txt_ValidateCode.Text))
{
    snCheckCode.Create();
    Utility.ShowMessage("校验码错误!");
    return;
}

string strUserName = txt_Username.Text.Trim();
string md5Pwd = Helper.MD5ForPHP(Helper.MD5ForPHP(txt_Password.Text));
lc_admin admin = null;
bool logined = false;

using (var context = new dbEntities())
{
    admin = context.tb_admin.Where(n => n.username == strUserName).FirstOrDefault();

    if (admin != null)
    {
        if (admin.checkadmin != "true")
        {
            snCheckCode.Create();
            Utility.ShowMessage("抱歉,该账号被禁止登录!");
            return;
        }

        if (admin.password == md5Pwd)
        {
            // Update Admin Info
            admin.loginip = Request.UserHostAddress.ToString();
            admin.logintime = CndingUtility.DateTimeToUnixTimeStamp(DateTime.Now);
            context.SaveChanges();

            logined = true;
        }
    }
}

if (logined)
{
    // Login
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
        1,
        admin.id.ToString(),
        DateTime.Now,
        DateTime.Now.AddMinutes(60),
        false,
        "Admin",
        FormsAuthentication.FormsCookiePath
        );
    string hashTicket = FormsAuthentication.Encrypt(ticket);
    HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
    HttpContext.Current.Response.Cookies.Add(userCookie);

    if (Request["ReturnUrl"] != null)
    {
        Response.Redirect(HttpUtility.HtmlDecode(Request["ReturnUrl"]));
    }
    else
    {
        Response.Redirect("/manager/default.aspx");
    }
}
else
{
    snCheckCode.Create();
    CndingUtility.ShowMessage("用户名或密码不正确!");
}
复制代码

MD5加密代码:

复制代码
public static string MD5ForPHP(string stringToHash)
{
    var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
    byte[] emailBytes = Encoding.UTF8.GetBytes(stringToHash.ToLower());
    byte[] hashedEmailBytes = md5.ComputeHash(emailBytes);
    StringBuilder sb = new StringBuilder();
    foreach (var b in hashedEmailBytes)
    {
        sb.Append(b.ToString("x2").ToLower());
    }
    return sb.ToString();
}
复制代码

  认证成功后默认会将用户登录信息以Cookie的形式存放到客户端,有效期为60分钟。UserData被设置为用户的角色,在判断用户是否登录时会用到。如下面的代码:

复制代码
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
    int adminId = -1;
    FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;
    FormsAuthenticationTicket ticket = identity.Ticket;
    string userData = ticket.UserData;
    if (userData == "Admin")
    {
        // To do something
    }
}
复制代码

   上述代码在Visual Studio中运行一切正常!但是将网站发布到服务器的IIS (可能会是较低版本的IIS,如IIS 6)后,发现登录功能异常。输入用户名和密码后点击登录按钮,页面postback但并不能正确跳转,尝试手动访问受保护的页面会被自动跳转回登录页面。更奇怪的是该问题只出现在IE11浏览器上,尝试用Firefox或Chrome访问登录功能运行正常。初步怀疑是IIS设置的问题,可是IIS 6上并没有与Cookie相关的设置,好像记得IIS 7上倒是有这个设置。但因为只有IE 11存在该问题,所以可以否定代码本身存在任何问题。

  此外,还尝试了降低IE 11的安全级别,重新安装服务器上的.net framework以及下载最新的补丁等等,均不能解决问题。后来发现其实只需要简单修改Web.config中authentication节点的设置就可以了,给forms添加cookieless="UseCookies"属性即可。

<authentication mode="Forms">
  <forms name="MyAuth" cookieless="UseCookies" loginUrl="manager/Login.aspx" defaultUrl="manager/default.aspx" protection="All" timeout="60" />
</authentication>

  用以明确告诉服务器使用Cookie来保存用户验证信息。问题解决!


本文转自Jaxu博客园博客,原文链接:http://www.cnblogs.com/jaxu/p/3698377.html,如需转载请自行联系原作者

相关文章
|
Web App开发 .NET Windows
IE10 IE11 中 网站无法登录问题cookie
方法一: 在程序文件中添加此文件 在项目中创建一个文件夹将下载的文件直接拖入文件夹中 来源于:http://www.hanselman.com/blog/BugAndFixASPNETFailsToDetectIE10CausingDoPostBackIsUndefinedJavaScriptErrorOrMaintainFF5ScrollbarPosition.
1042 0
|
.NET Windows 开发框架
IE10、IE11 User-Agent 导致的 ASP.Net 网站无法写入Cookie 问题
原文:IE10、IE11 User-Agent 导致的 ASP.Net 网站无法写入Cookie 问题      你是否遇到过当使用一个涉及到Cookie操作的网站或者管理系统时,IE 6、7、8、9下都跑的好好的,唯独到了IE10、11这些高版本浏览器就不行了?好吧,这个问题码农连续2天内遇到了2次。
1156 0
|
2月前
|
存储 自然语言处理 API
Session、cookie、token有什么区别?
Session、cookie、token有什么区别?
24 1
|
3月前
|
存储 开发框架 NoSQL
ASP.NET WEB——项目中Cookie与Session的用法
ASP.NET WEB——项目中Cookie与Session的用法
39 0
|
3月前
|
存储 安全 API
Cookie,Session和Token
Cookie,Session和Token
|
5天前
|
存储 缓存 安全
【PHP开发专栏】PHP Cookie与Session管理
【4月更文挑战第30天】本文介绍了PHP中的Cookie和Session管理。Cookie是服务器发送至客户端的数据,用于维持会话状态,可使用`setcookie()`设置和`$_COOKIE`访问。Session数据存于服务器,更安全且能存储更多数据,通过`session_start()`启动,`$_SESSION`数组操作。根据需求选择Cookie(跨会话共享)或Session(单会话存储)。实战中常组合使用,如Cookie记住登录状态,Session处理购物车。理解两者原理和应用场景能提升Web开发技能。
|
9天前
|
存储 安全 前端开发
禁用Cookie后Session还能用吗?
禁用Cookie后Session还能用吗?
18 1
|
9天前
|
Java
Cookie和Session
Cookie和Session
16 0
|
20天前
|
存储 JSON 安全
|
23天前
|
存储 前端开发 数据安全/隐私保护
网站开发--Cookie 和 Session 的工作流程
网站开发--Cookie 和 Session 的工作流程
18 0