【问题标题】:How to get recently authenticated user?如何获取最近通过身份验证的用户?
【发布时间】:2011-11-23 08:38:21
【问题描述】:

我正在使用 MVC 3,我刚刚为 FormsAuthenticationService 实现了一个包装器。

类似于以下内容。

public void SignIn(string username, bool createPersistantCookie)
{
    if (string.IsNullOrEmpty(username)) 
        throw new ArgumentException("Value Cannot be null or empty", "username");

    FormsAuthentication.SetAuthCookie(username, createPersistantCookie);
}

很不情愿,我已经让它工作了,但现在我不太确定如何获取我存储的信息。

一旦用户进入我的系统,如果我需要从数据库中获取他们的 UserID,我现在如何安全地检索此信息?

【问题讨论】:

  • 您需要检索什么类型的信息?只是他们的UserId?如果是这样,则可以将其存储在表单 cookie 中,而无需访问数据库。请澄清。

标签: c# security asp.net-mvc-3 authentication cookies


【解决方案1】:

根据提供的附加信息,您希望使用 FormsAuthentication 票证存储附加数据。为此,您需要首先创建一个自定义 FormsAuthentication 票证:

存储数据

获取当前的HttpContext(不用担心可测试性)

var httpContext = HttpContext.Current;

确定票证何时到期:

var expires = isPersistent 
                ? DateTime.Now.Add(FormsAuthentication.Timeout) 
                : NoPersistenceExpiryDate; // NoPersistenceExpiryDate = DateTime.MinValue

创建一个新的 FormsAuthentication 票证来保存您的自定义数据。

var authenticationTicket = new FormsAuthenticationTicket(
                             1, 
                             username, 
                             DateTime.Now, 
                             DateTime.Now.Add(FormsAuthentication.Timeout), 
                             isPersistent, 
                             "My Custom Data String"); //Limit to about 1200 bytes max

创建您的 HTTP cookie

new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authenticationTicket))
  {
    Path = FormsAuthentication.FormsCookiePath,
    Domain = FormsAuthentication.CookieDomain,
    Secure = FormsAuthentication.RequireSSL,
    Expires = expires,
    HttpOnly = true
  };

最后添加到响应中

httpContext.Response.Cookies.Add(cookie);

检索数据

然后您可以通过解析存储的身份验证票证来检索后续请求的数据...

再次,获取当前的 HttpContext

var httpContext = HttpContext.Current

检查请求是否已通过身份验证(在 Application_AuthenticateRequest 或 OnAuthorize 中调用)

if (!httpContext.Request.IsAuthenticated)
    return false;

检查您是否有可用的 FormsAuthentication 票证并且它尚未过期:

var formsCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (formsCookie == null)
  return false;

检索 FormsAuthentication 票证:

var authenticationTicket = FormsAuthentication.Decrypt(formsCookie.Value);
if (authenticationTicket.Expired)
  return false;

最后检索您的数据:

var data = authenticationTicket.UserData;

【讨论】:

    【解决方案2】:

    您实际上并未在数据库中存储用户 ID。您编写的所有代码都是在用户计算机上存储身份验证 cookie,或者作为会话 cookie(非持久性)或作为持久性 cookie。

    当您的页面刷新时,它会自动获取 cookie,对其进行解码,并填充您从控制器的 User.Current 属性访问的 IPrincipal 对象。

    【讨论】:

    • 我很抱歉,我真的只是错误地解释了我的问题。我的意思是如何访问我刚刚存储在 cookie 中的内容。我计划最终存储除用户名之外的其他内容,我只想知道如何从 cookie 中访问它...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 2017-11-29
    相关资源
    最近更新 更多