首页 > 解决方案 > 如何从 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 令牌解码的用户设置为登录用户,并且传入的角色 admin 用于授权

标签: c#jwtasp.net-core-2.2

解决方案


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

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


推荐阅读