Asp.NetCore 登录验证

第一步

在startup中注册

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
                {
                    o.Cookie.Name = "SSO_Login";
                    o.Cookie.Expiration = new TimeSpan(0, 0, 30);
                    o.LoginPath = new PathString("/SSO/Account/Login");            //登录路径:这是当用户试图访问资源但未经过身份验证时,程序将会将请求重定向到这个相对路径。
                    o.AccessDeniedPath = new PathString("/SSO/Account/Login");     //禁止访问路径:当用户试图访问资源时,但未通过该资源的任何授权策略,请求将被重定向到这个相对路径。
                    o.SlidingExpiration = true; //Cookie可以分为永久性的和临时性的。 临时性的是指只在当前浏览器进程里有效,浏览器一旦关闭就失效(被浏览器删除)。 
                              永久性的是指Cookie指定了一个过期时间,在这个时间到达之前,此cookie一直有效(浏览器一直记录着此cookie的存在)。
                              slidingExpriation的作用是,指示浏览器把cookie作为永久性cookie存储,但是会自动更改过期时间,以使用户不会在登录后并一直活动,但是一段时间后却自动注销。
                              也就是说,你10点登录了,服务器端设置的TimeOut为30分钟,如果slidingExpriation为false,那么10: 30以后,你就必须重新登录。如果为true的话,
                              你10: 16分时打开了一个新页面,服务器就会通知浏览器,把过期时间修改为10: 46。
});

第二步

登录时候的代码

        [HttpGet]
        public async Task<IActionResult> SsoLogin(string accessCode)
        {
            //如果用户已经登录,直接跳转到登录成功页面
            var checkResult=await DcAPI.Instance.CheckIsLogin(accessCode);
            if (!checkResult.IsSuccess)
                return new EmptyResult();
            if (checkResult.NotNullData().IsLogin)
            {
                var claims = new List<Claim>()
                {
                    new Claim(ClaimTypes.Name,checkResult.NotNullData().UserInfo.Name)
                };
                ClaimsIdentity identity = new ClaimsIdentity(claims,"SsoLogin");
                ClaimsPrincipal principal = new ClaimsPrincipal(identity);
                await HttpContext.SignInAsync(principal);

                return new EmptyResult();
            }
            else
            {
                return new JsonResult(new ResultMo(ResultCode.NotLogin, "您还未登录。"));
            }

        }

  

第三步

在controller中打上需要验证的标志

  [Authorize]
    public class HomeController : Controller
    {
}

 

posted @ 2020-07-29 11:42  hello_stone  阅读(207)  评论(0)    收藏  举报