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

.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()


特别声明:本站部分内容收集于互联网是出于更直观传递信息的目的。该内容版权归原作者所有,并不代表本站赞同其观点和对其真实性负责。如该内容涉及任何第三方合法权利,请及时与824310991@qq.com联系,我们会及时反馈并处理完毕。