使用ASP.NET Identity 2.0和MVC 5进行自定义单点登录

N1n*_*B0b 5 asp.net authentication asp.net-mvc asp.net-mvc-5 asp.net-identity

我正在使用Identity 2.0在MVC 5中重写我的MVC 4表单身份验证应用程序.

目前,该站点使用专有的单点登录方法,该方法从POST请求解密传入参数,并根据内容的有效性,使用FormsAuthentication.SetAuthCookie设置身份验证cookie并将用户重定向到安全内容.

既然我正在使用ASP.Net Identity,那么FormsAuthentication.SetAuthCookie功能的适当替代是什么?请记住,我不想将这些用户中的任何一个持久化到数据库中.它们应该存在于其令牌/ cookie中.

N1n*_*B0b 3

知道了!我在这篇有用的文章中找到了解决方案。

基本上,您创建一个 ClaimsIdentity,然后使用 OWINContext 中的 AuthenticationManager 来“登录”该身份并创建身份验证 cookie。

像这样:

var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "Brock"));
claims.Add(new Claim(ClaimTypes.Email, "brockallen@gmail.com"));
var id = new ClaimsIdentity(claims,DefaultAuthenticationTypes.ApplicationCookie);

var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(id);
Run Code Online (Sandbox Code Playgroud)