在ASP.NET Core Identity外面使用Cookie中间件

来源:互联网 发布:推荐软件推荐 知乎 编辑:程序博客网 时间:2024/06/05 03:08
1、在 app.UseMvc 前面加上app.UseCookieAuthentication
  1. app.UseCookieAuthentication(new CookieAuthenticationOptions()
  2. {
  3. AuthenticationScheme = "IdeaCoreUser",
  4. LoginPath = new PathString("/Login/Login/"),
  5. AccessDeniedPath = new PathString("/Account/Forbidden/"),
  6. AutomaticAuthenticate = true,
  7. AutomaticChallenge = true,
  8. CookieDomain=""
  9. });
2、登录
  1. var claims = new List<Claim> {
  2. new Claim("FullName", customer.Username,ClaimValueTypes.String),
  3. new Claim("Role", "注册用户",ClaimValueTypes.String),
  4. };
  5. var userIdentity = new ClaimsIdentity(claims, "Customer");
  6. var userPrincipal = new ClaimsPrincipal(userIdentity);
  7. HttpContext.Authentication.SignInAsync("IdeaCoreUser", userPrincipal,
  8. new AuthenticationProperties
  9. {
  10. ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
  11. IsPersistent = false,
  12. AllowRefresh = false
  13. });
3、退出登录
  1. HttpContext.Authentication.SignOutAsync("IdeaCoreUser");
4、判断是否已经登录
  1. var bol =HttpContext.User.Identity.IsAuthenticated;
5、使用IIdentity拓展方法来获取存的值
  1. public static class IdentityExtension
  2. {
  3. public static string FullName(this IIdentity identity)
  4. {
  5. var claim = ((ClaimsIdentity)identity).FindFirst("FullName");
  6. return (claim != null) ? claim.Value : string.Empty;
  7. }
  8. public static string Role(this IIdentity identity)
  9. {
  10. var claim = ((ClaimsIdentity)identity).FindFirst("Role");
  11. return (claim != null) ? claim.Value : string.Empty;
  12. }
  13. }
  1. var fullname = HttpContext.User.Identity.FullName();

0 0
原创粉丝点击