目之瞬间-专注于互联网平台

.net5 基于cookie简单身份验证使用

依赖 Microsoft.AspNetCore.Authentication


HttpContext.User.Identity.IsAuthenticated 始终返回false 原因有可能为

在.net core 2.x 以后最好包括authenticationScheme、identity、auth属性

//ConfigureServices 配置
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
 .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
 {  o.Cookie.Name = "xxxx"; });
//Configure 配置
 app.UseAuthentication();
 app.UseAuthorization();

在api或view 里面使用,统一验证处理可使用中间件的形式处理

//记录登陆信息写入cookis
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);

                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, username));
                identity.AddClaim(new Claim(ClaimTypes.Name, username));
                identity.AddClaim(new Claim(ClaimTypes.Role, "User"));

                var principal = new ClaimsPrincipal(identity);

                var authProperties = new AuthenticationProperties
                {
                    AllowRefresh = true,
                    ExpiresUtc = DateTimeOffset.Now.AddDays(30),
                    IsPersistent = true,
                };
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(principal), authProperties);

退出使用

HttpContext.SignOutAsync()