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

时间:2019-07-19 14:23:58

标签: c# jwt asp.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用于授权

1 个答案:

答案 0 :(得分:0)

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

我假设您已将控制器设置为使用[Authorize]属性,并在IServiceCollection配置中启用了Authorization东西?

相关问题