asp.net mvc的身份验证cookie问题 [英] asp.net mvc authentication cookie issue

查看:218
本文介绍了asp.net mvc的身份验证cookie问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现使用ASP.NET MVC一个记住我的功能。它使用了定制的认证过程如下所定义。

I'm trying to implement a "remember me" feature using ASP.NET MVC. It uses a customized authentication process as defined below.

Web.config文件:

Web.config:

    <authentication mode="Forms">
        <forms loginUrl="/Account/Login" defaultUrl="/Home/MyAccount" timeout="43200"/>
    </authentication>

code坚持的cookie:

Code to persist cookie:

public void SignIn(string userName, bool createPersistentCookie) {
    int timeout = createPersistentCookie ? 525600 : 120; // Timeout in minutes, 525600 = 365 days.
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(userName, createPersistentCookie, timeout);
    string encrypted = FormsAuthentication.Encrypt(ticket);
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
    cookie.Expires = System.DateTime.Now.AddMinutes(timeout);

    HttpContext.Current.Response.Cookies.Add(cookie);
    FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}

code检索的cookie:

Code to retrieve cookie:

        if (System.Web.HttpContext.Current.Request.Cookies.AllKeys.Contains(FormsAuthentication.FormsCookieName)) {
            cookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
        }

目前的code检查会话进行身份验证。我想补充摆脱cookie中的用户名作为很好的能力。我有2个问题:

The current code checks for Session for authentication. I'd like to add the ability to get the userName from cookie as well. I have 2 questions:


  1. 我需要什么,以便检索该cookie办?

  2. 如何解密cookie来获取用户名?

干杯,

院长

推荐答案

要获取的cookie:

To get the cookie:

HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);

与解密:

FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
var userName = ticket.UserData

这篇关于asp.net mvc的身份验证cookie问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆