如何获得最近经过身份验证的用户

本文关键字:用户 身份验证 经过 何获得 最近 | 更新日期: 2023-09-27 18:09: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,我现在如何安全地检索这些信息?

如何获得最近经过身份验证的用户

根据提供的附加信息,您希望使用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;

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

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