如何从 jwt 令牌登录用户并设置角色 .net Core 2.2



我已经设法解码了 jwt 令牌并创建了一个主体,但是当我使用 HttpContext.SignInUserAsync 时,没有用户登录

      public async Task<ActionResult> Index()
       {
           if (Data.accessToken == null)
           {
               var token = await HttpContext.GetTokenAsync(CookieAuthenticationDefaults.AuthenticationScheme, "access_token");
               if (string.IsNullOrEmpty(token))
               {
                   return RedirectToAction("signin", "Authentication");
               }
               Data.accessToken = token;
               var handler = new JwtSecurityTokenHandler();
               var tokenS = handler.ReadToken(Data.accessToken) as JwtSecurityToken;

               if (!User.Identity.IsAuthenticated)
               {

                   var claims = new List<Claim>
                       {
                           new Claim(ClaimTypes.Name, tokenS.Claims.ElementAt(1).Value),
                           new Claim("FullName", tokenS.Claims.ElementAt(1).Value),
                           new Claim(ClaimTypes.Role, "Admin"),
                       };
                   Data.EMAIL = tokenS.Claims.ElementAt(1).Value;
                   var claimsIdentity = new ClaimsIdentity(
                       claims, CookieAuthenticationDefaults.AuthenticationScheme);

                   await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), new AuthenticationProperties { IsPersistent = true });

                   return Redirect("/");

               }
           }
           return View();
       }

我希望从 jwt 令牌解码的用户设置为登录用户,并将传入的角色管理员用于授权

你不需要像那样手动读取令牌。Net Core神奇地为你做到了这一点。例如,控制器中的HttpContext.Current.User.Identity将为您提供有效的登录用户,前提是您已正确配置其他所有内容。

我假设您已将控制器设置为使用属性 [授权] 属性并在 IServiceCollection 配置中启用了授权内容?

最新更新