使用HttpContext.SignInAsync实现简单的授权


1.  将认证添加到服务中

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                //登入地址
                options.LoginPath = "/Account/FcbLogin/";
                //登出地址
                options.LogoutPath = "/Account/FcbLogout/";
                //设置cookie过期时长
                //options.ExpireTimeSpan = TimeSpan.FromSeconds(10);
            });

所有CookieAuthenticationOptions 属性可以查看微软官方文档

 

2. 注入管道

这里认证要在授权之前注入

app.UseAuthentication();

3. 添加登入和登出

这里我没有验证用户账号密码,只是写了登入和登出的相关代码,这里也可以喝注入认证那里一样,这是票证过期时间

        [HttpPost]
        public async Task Login(UserLogin model)
        {
            //这里的scheme一定要和注入服务的scheme一样
            var identity = new ClaimsIdentity(new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme));
            //自定义的claim信息
            identity.AddClaim(new Claim("abc", "123"));
            AuthenticationProperties properties = new AuthenticationProperties()
            {
                //设置cookie票证的过期时间
                ExpiresUtc = DateTime.Now.AddDays(1),
                RedirectUri = model.ReturnUrl
            };
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), properties);

            if (string.IsNullOrEmpty(model.ReturnUrl))
            {
                return LocalRedirect("/");
            }
            return LocalRedirect(model.ReturnUrl);
        }
        [HttpGet]
        public ActionResult FcbLoginOut()
        {
            //AuthenticationProperties properties = new AuthenticationProperties()
            //{
            //    ExpiresUtc = DateTime.Now.AddDays(-100)
            //};
            HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return Ok();
        }