1、在 app.UseMvc 前面加上app.UseCookieAuthentication
app.UseCookieAuthentication(new CookieAuthenticationOptions() { AuthenticationScheme = "IdeaCoreUser", LoginPath = new PathString("/Login/Login/"), AccessDeniedPath = new PathString("/Account/Forbidden/"), AutomaticAuthenticate = true, AutomaticChallenge = true, CookieDomain="" });
2、登录
var claims = new List{ new Claim("FullName", customer.Username,ClaimValueTypes.String), new Claim("Role", "注册用户",ClaimValueTypes.String),};var userIdentity = new ClaimsIdentity(claims, "Customer");var userPrincipal = new ClaimsPrincipal(userIdentity);HttpContext.Authentication.SignInAsync("IdeaCoreUser", userPrincipal, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddMinutes(20), IsPersistent = false, AllowRefresh = false });
3、退出登录
HttpContext.Authentication.SignOutAsync("IdeaCoreUser");
4、判断是否已经登录
var bol =HttpContext.User.Identity.IsAuthenticated;
5、使用IIdentity拓展方法来获取存的值
public static class IdentityExtension { public static string FullName(this IIdentity identity) { var claim = ((ClaimsIdentity)identity).FindFirst("FullName"); return (claim != null) ? claim.Value : string.Empty; } public static string Role(this IIdentity identity) { var claim = ((ClaimsIdentity)identity).FindFirst("Role"); return (claim != null) ? claim.Value : string.Empty; } }
var fullname = HttpContext.User.Identity.FullName();