asp.net-mvc - asp.net mvc身份验证cookie问题

标签 asp.net-mvc

我正在尝试使用 ASP.NET MVC 实现“记住我”功能。它使用如下定义的自定义身份验证过程。

Web.config:

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

保存 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);
}

获取cookie的代码:

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

当前代码检查 session 以进行身份​​验证。我还想添加从 cookie 获取用户名的功能。我有两个问题:

  1. 我需要做什么才能检索 Cookie?
  2. 如何解密 cookie 以获得用户名?

最佳答案

获取cookie:

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

解密它:

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

关于asp.net-mvc - asp.net mvc身份验证cookie问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4029369/

相关文章:

asp.net-mvc - 将数据对象临时保存在 MVC Controller 、MVC、MVC Controller 临时存储中

asp.net-mvc - ASP.NET MVC IDENTITY_INSERT 设置为 OFF

asp.net - 使用css设置kendoui样式文本框的宽度

c# - 将 ASP MVC 应用程序部署到普通共享托管服务提供商时遇到问题

asp.net-mvc - typeahead.js 在同一文本元素中选择多个值

c# - 具有可动态切换数据类型的文本框的 MVC 4 客户端验证

asp.net-mvc - 从基本 Controller 重定向到操作方法

jquery - ajax 调用未命中 MVC 操作结果

C#以更少的内存消耗从服务器下载大文件

c# - 如何在名称中指定带有 - 的属性