简体   繁体   English

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

[英]How to get recently authenticated user?

I am working with MVC 3 and I have just implemented a wrapper for the FormsAuthenticationService. 我正在使用MVC 3,并且刚刚为FormsAuthenticationService实现了包装。

Something similar to the following. 类似于以下内容。

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

Reluctantly, I have gotten this to work, but now I am not quite sure how to get the information that I have stored. 我很不情愿地使它起作用,但现在我不太确定如何获取已存储的信息。

Once the user is in my system, how can I now safely retrieve this information if I need to grab their UserID out of the database? 一旦用户进入我的系统,如果我需要从数据库中获取他们的UserID,现在如何安全地检索此信息?

Based on the additional information provided, you want to store additional data with the FormsAuthentication ticket. 根据提供的其他信息,您想使用FormsAuthentication票证存储其他数据。 To do so, you need first create a custom FormsAuthentication ticket: 为此,您需要首先创建一个自定义FormsAuthentication票证:

Storing Data 储存资料

Grab the current HttpContext (not worrying about testability) 获取当前的HttpContext(不必担心可测试性)

var httpContext = HttpContext.Current;

Determine when the ticket should expire: 确定票证何时到期:

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

Create a new FormsAuthentication ticket to hold your custom data. 创建一个新的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

Create your HTTP cookie 创建您的HTTP cookie

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

And finally add to the response 最后添加到响应中

httpContext.Response.Cookies.Add(cookie);

Retrieving Data 检索数据

Then you can retrieve your data on subsequent requests by parsing the stored authentication ticket... 然后,您可以通过解析存储的身份验证凭单来检索后续请求的数据...

Again, grab current HttpContext 再次,获取当前的HttpContext

var httpContext = HttpContext.Current

Check to see if the request has been authenticated (call in Application_AuthenticateRequest or OnAuthorize) 检查请求是否已通过身份验证(调用Application_AuthenticateRequest或OnAuthorize)

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

Check to see if you have a FormsAuthentication ticket available and that it has not expired: 检查是否有可用的FormsAuthentication票证,并且该票证尚未过期:

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

Retrieve the FormsAuthentication ticket: 检索FormsAuthentication票证:

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

And finally retrieve your data: 最后检索您的数据:

var data = authenticationTicket.UserData;

You haven't actually stored a user id in the database. 您实际上尚未在数据库中存储用户ID。 All the code that you've written does is store an authentication cookie on the users computer, either as a session cookie (not persistent) or as a persistent one. 您编写的所有代码都是将身份验证cookie存储在用户计算机上,既可以作为会话cookie(不是永久性的),也可以作为持久性cookie。

When your page refreshes, it will get the cookie automatically, decode it, and populate the IPrincipal object which you access from the User.Current property of your controller. 页面刷新时,它将自动获取cookie,对其进行解码,并填充您从控制器的User.Current属性访问的IPrincipal对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM