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

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

我正在使用 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/

相关文章:

c# - 如何使用 Simple Injector 注册 Drum.UriMaker<>?

c# - 如何在 WindowsPhone/Windows 8.1 上按下 Enter 键时隐藏软键盘?

c# - 如何通过 JavaScript 回调在 C# 中运行 QUnit 测试并返回测试结果?

javascript - 如何限制对我的网络服务的访问?

java - Java 中的安全通信 - 序列化密文对象与传输层加密与 SSL 上的 RMI

C# 音频库

angularjs - 在基于浏览器的应用程序中,我在哪里存储 OAuth 刷新 token

asp.net-mvc - 在 ASP.NET MVC 3 中自定义模型绑定(bind)错误消息

asp.net-mvc-3 - 如何在 MVC3 中显示数组

asp.net-mvc - 返回部分 View 的 RedirectToAction 如何返回完整 View ?