zoukankan      html  css  js  c++  java
  • .net core中登录认证---中间件认证

    .net core中登录认证---中间件认证  

    介绍:这是基于授权认证中间件认证的示例

    第一步:

    在 app.UseRouting();之后,在app.UseEndpoints()之前,增加鉴权授权;
    鉴权: app.UseAuthentication();---检测用户是否登录
    授权:app.UseAuthorization();//授权 检测有没有权限,是否能够访问后续的页面功能

    第二步:在ConfigureServices中中增加如下

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = new PathString("/Login/Login"); //如果授权失败,就跳转到这个路径去中
    
    //options.AccessDeniedPath = new PathString("/Home/Privacy");
    });//用cookie

    第三步:第三步:指定哪些Action需要做鉴权授权,标记特性:标记在哪个Action上,哪个Action就能够支持鉴权授权,也可以标记在控制器,全局;

    [Microsoft.AspNetCore.Authorization.Authorize]

    第四步: 登录时使用鉴权

             [HttpPost]
         [AllowAnonymousAttribute] //这是匿名,加上他会避开权限检查
    public IActionResult Login(string name,string password) { string verifyCode = base.HttpContext.Session.GetString("CheckCode"); if (!string.IsNullOrEmpty(verifyCode)) { } #region 鉴权:鉴权,检测有没有登录,登录的是谁,赋值给User //rolelist 是登录成功后用户的角色---是来自于数据库的查询;不同的用户会查询出不同的角色; var rolelist = new List<string>() { "Admin", "Teacher", "Student" }; //ClaimTypes.Role就是做权限认证的标识; var claims = new List<Claim>()//鉴别你是谁,相关信息 { new Claim(ClaimTypes.Role,"Admin"), new Claim(ClaimTypes.Name,name), new Claim("password",password),//可以写入任意数据 new Claim("Account","Administrator"), new Claim("role","admin"), new Claim("zhaoxi","zhaoxi"), new Claim("User","zhaoxi") }; foreach (var role in rolelist) { claims.Add(new Claim(ClaimTypes.Role, role)); } ClaimsPrincipal userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer")); HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddMinutes(30),//过期时间:30分钟 }).Wait(); #endregion var user = HttpContext.User; return base.Redirect("/Home/Index"); }

    第五步:鉴权授权角色授权,不同的用户,可能会存在不同的角色,不同的角色,可能在访问不同的页面的时候,需要做不同拦截;----角色授权其实就是通过角色不同,做不同的权限拦截;

    [Authorize(Roles = "Admin,Teacher,Student")]

    六、用户退出登录

    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

    谢谢学习!!!关注我,每天进步一点点

  • 相关阅读:
    Nginx 和 PHP的安装配置
    hdu1166 敌兵布阵
    乘法逆元详解
    SPFA算法
    Kruskal算法&Prim算法
    WC2018 文艺汇演《退役的你》
    HDU2577 How to Type
    裴蜀定理的证明
    CSP J/S 2019受虐记
    Dijkstra算法详解
  • 原文地址:https://www.cnblogs.com/wangjinya/p/14535023.html
Copyright © 2011-2022 走看看