首页 > Windows开发 > 详细

MVC6 OWin Microsoft Identity 自定义验证

时间:2016-01-18 12:08:47      阅读:984      评论:0      收藏:0      [点我收藏+]
1、 Startup.cs中修改默认的验证设置
  1. //app.UseIdentity();
  2. app.UseCookieAuthentication(options => {
  3. //options.AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme;// "MyCookieMiddlewareInstance";
  4. options.LoginPath = new PathString("/Account/Unauthorized/");
  5. options.AccessDeniedPath = new PathString("/Account/Forbidden/");
  6. options.AutomaticAuthenticate = true;
  7. options.AutomaticChallenge = true;
  8. });

  1. using System.Security.Claims;
  2. using Microsoft.AspNet.Authentication.Cookies;
  3. using Microsoft.AspNet.Identity;
2、Controller中的登录代码
  1. public async Task<IActionResult> Login()
  2. {
  3. var claims = new List<Claim>();
  4. claims.Add(new Claim(ClaimTypes.Name, "Admin")); // value of this.User.GetUserName() or this.User.Identity.Name
  5. claims.Add(new Claim(ClaimTypes.NameIdentifier, "10001")); // value of this.User.GetUserId();
  6. claims.Add(new Claim("SelfDefined1", "value1"));
  7. var ci = new System.Security.Claims.ClaimsIdentity(claims, IdentityCookieOptions.ApplicationCookieAuthenticationType);
  8. var cp = new System.Security.Claims.ClaimsPrincipal(ci);
  9. await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, cp );
  10. return View("Index");
  11. }
注意,在创建ClaimsIdentity时, AuthenticationType 参数是必须的。
因为 this.User.IsSignedIn(); 是靠这个参数带验证是否登录的。

3、Controller中取登录信息的代码:
  1. bool signed = this.User.IsSignedIn();
  2. string userName = this.User.Identity.Name;
  3. userName = this.User.GetUserName();
为了使用方便,常定义一些  ClaimsPrincipal(this.User) 的扩展方法来取各种登录时保存的变量。
 




MVC6 OWin Microsoft Identity 自定义验证

原文:http://www.cnblogs.com/ybst/p/5138565.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!