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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值