我正在使用 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);
}
不情愿地,我已经让它工作了,但现在我不太确定如何获取我存储的信息。
一旦用户进入我的系统,如果我需要从数据库中获取他们的用户 ID,我现在如何安全地检索此信息?
最佳答案
根据提供的附加信息,您希望使用 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;
关于c# - 如何获得最近通过身份验证的用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7524136/