持久性AuthCookie已设置,但被重定向到登录

时间:2015-04-28 14:56:57

标签: c# asp.net forms-authentication

我在使用持久性AuthCookie时遇到问题。验证和登录工作完美,如果我关闭浏览器并重新打开它,验证仍然有效,不会重定向到登录页面。 我不知道确切的时间是什么,但是让我们说如果关闭浏览器而不注销并且只在20分钟后重新打开它,我将被重定向到登录页面,即使cookie是当我查看网络开发者工具时设置,它的到期日期是从现在开始的一个月。

验证用户凭据后我所做的全部是

FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

在我的Web.Config中我将其设置为

<configuration>
    <system.web>
    ...
    <authentication mode="Forms">
        <forms cookieless="UseCookies" loginUrl="~/Utilizador/Login" name="SMOAuth" slidingExpiration="true" timeout="43829"/>
    </authentication>
    ...

还尝试按照建议here和其他一些地方对机器密钥进行硬编码,但没有效果

<machineKey validationKey="Validation_Key_Here" decryptionKey="Decrypt_Key_Here" validation="SHA1" decryption="AES"/>

我很难解决这个问题

1 个答案:

答案 0 :(得分:4)

//this line is NOT ENOUGH for "remember me" to work!!!
FormsAuthentication.SetAuthCookie(userName, true); //DOESN'T WORK!

//###########

//you have to save the "remember me" info inside the auth-ticket as well
//like this:

DateTime expires = DateTime.Now.AddDays(20); //remember for 20 days

//create the auth ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
    userName,
    DateTime.Now,
    expires, // value of time out property
    true, // Value of IsPersistent property!!!
    String.Empty,
    FormsAuthentication.FormsCookiePath);

//now encrypt the auth-ticket
string encryptedTicket = FormsAuthentication.Encrypt(ticket);

//now save the ticket to a cookie
HttpCookie authCookie = new HttpCookie(
            FormsAuthentication.FormsCookieName,
            encryptedTicket);
authCookie.Expires = expires;

//feed the cookie to the browser
HttpContext.Current.Response.Cookies.Add(authCookie);