编程语言
首页 > 编程语言> > c# – 已设置持久性AuthCookie,但被重定向到登录状态

c# – 已设置持久性AuthCookie,但被重定向到登录状态

作者:互联网

我在使用持久性AuthCookie时遇到问题.验证和登录工作完美,如果我关闭浏览器并重新打开它,验证仍然有效,不会重定向到登录页面.
我不确定具体的时间是什么,但是让我们说如果关闭浏览器而不注销并且仅在20分钟后重新打开它,我将被重定向到登录页面,即使我在使用web开发人员工具检查时设置了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"/>

我正在努力解决这个问题

解决方法:

//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);

标签:c,asp-net,forms-authentication
来源: https://codeday.me/bug/20190609/1205036.html