zoukankan      html  css  js  c++  java
  • MVC6 OWin Microsoft Identity 自定义验证

    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) 的扩展方法来取各种登录时保存的变量。
     




  • 相关阅读:
    wc 统计程序
    读C#程序
    VS2013 单元测试
    android开发心得之知识的量变到质变
    大学第一篇博客
    团队作业七
    团队作业六
    团队作业五
    团队作业四
    团队作业三
  • 原文地址:https://www.cnblogs.com/ybst/p/5138565.html
Copyright © 2011-2022 走看看