详细解释 http://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/我正在寻找一种使用 OWIN 而不是 FormsAuthentication 的方法,但没有所有用户管理器、用户存储的东西。我想你也想要同样的。
在您的登录操作中,使用您自己的代码检查数据库中的用户凭据,如果用户正确,则使用所需信息创建声明并使用这些声明调用 AuthenticationManager.SignIn:
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
,new Claim(ClaimTypes.Name, user.UserName)
,new Claim(ClaimTypes.Email, user.Email)
};
var identity = new ClaimsIdentity(claims,
DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
现在您就像 FormsAuthentication.SetAuthCookie 方法一样登录。
现在您可以通过声明获取用户信息:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
var ctx = filterContext.HttpContext.Request.GetOwinContext();
var identity = (ClaimsPrincipal)filterContext.HttpContext.User;
var enumerable = identity.Claims as IList<Claim> ?? identity.Claims.ToList();
var username = enumerable.Where(x => x.Type == ClaimTypes.Name).Select(x => x.Value).FirstOrDefault();
var userId = enumerable.Where(x => x.Type == ClaimTypes.NameIdentifier).Select(x => x.Value).FirstOrDefault();
}
base.OnActionExecuting(filterContext);
}
您可以控制它,而不是 MVC 模板附带的所有 EF Code First 内容