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




  • 相关阅读:
    Linux硬盘分区方案
    mysql笔记四:索引查询及处理
    thread 学习笔记
    mysql笔记二:基本数据库、表查询操作
    linux 自学系列:监测端口占用情况
    linux 自学系列:命令行传输文件
    mysql笔记三:基本数据库、表创建更新操作
    mysql笔记五:权限管理
    threading源代码问题,为什么要将引入的变量del?
    linux 自学系列:更改系统语言编码
  • 原文地址:https://www.cnblogs.com/ybst/p/5138565.html
Copyright © 2020-2023  润新知