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");

        }

  

posted @ 2019-09-17 13:32  阿拉木木  阅读(4232)  评论(0编辑  收藏  举报