net core web 登录认证实现
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(o =>
{
o.LoginPath = "/user/login";
});
app.UseRouting();
app.UseAuthentication(); //增加登录验证,注意顺序
app.UseAuthorization();
登录验证成功后:
var claims = new List<Claim>()
{
new Claim(ClaimTypes.Name, userInfo.Nickname),
new Claim(ClaimTypes.NameIdentifier, userInfo.ID.ToString()),
new Claim("Phone", userInfo.Phone)
};
var claimnsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
//它会自动发送token给客户端。并生成cookies
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimnsIdentity),
new AuthenticationProperties
{
IsPersistent = true
});
验证:
context.HttpContext.User.Identity.IsAuthenticated
取值:
string? Nickname = context.HttpContext.User.Identity.Name
string? uid = context.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value
string phone = context.HttpContext.User.FindFirst("Phone")?.Value ?? "18011112222";