authorize(权限验证)


Startup 中 ConfigureServices 插入

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = "MyCookieAuthenticationScheme";
                options.DefaultChallengeScheme = "MyCookieAuthenticationScheme";
                options.DefaultSignInScheme = "MyCookieAuthenticationScheme";

            })
            .AddCookie("MyCookieAuthenticationScheme", options =>
            {
                options.AccessDeniedPath ="/Home";
                options.LoginPath = "/Home";
            });

Configure 中增加

app.UseAuthentication();

 

控制器中使用

public JsonResult LoginCheck(string username, string password)
        {
            var user = _***.***(username, password); //检测用户是否正确
            
            if (user.code == 0)
            {
                var claims = new List<Claim>()
                {
                    new Claim(ClaimTypes.Sid,Convert.ToString(user.data.id)),
                    new Claim(ClaimTypes.Name,user.data.username),                    
                    //new Claim(ClaimTypes.Role,user.data.usergroup)
                };

                string groupstr = user.data.usergroup; //通过后台调用权限属性
                string[] GroupSplit = groupstr.Split(',');

                if (GroupSplit != null)
                {
                    for (int i = 0; i < GroupSplit.Length; i++)
                    {
                        claims.Add(new Claim(ClaimTypes.Role, GroupSplit[i]));
                    }
                }
                var identity = new ClaimsIdentity(claims, "Login");
                var userPrincipal = new ClaimsPrincipal(identity);
                HttpContext.SignInAsync("MyCookieAuthenticationScheme", userPrincipal, new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                    IsPersistent = false,
                    AllowRefresh = false
                });

            }
            return Json(new { code = user.code, msg = user.result, data = user.data });
        }

 

获取结果

var userId = User.FindFirst(ClaimTypes.Sid).Value;
            var userName = User.Identity.Name;
            var rolelist = User.FindAll(ClaimTypes.Role);
            HttpContext.Response.WriteAsync($"测试结果  {userId}---{userName}--{rolelist}");

 

退出登录

public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync("MyCookieAuthenticationScheme");
            return RedirectToAction("Index", "Home");

        }

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM