c# - 如何从 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 用于授权
解决方案
您不需要像那样手动读取令牌。Net Core 神奇地为您做到了。例如,控制器中的 HttpContext.Current.User.Identity 将为您提供有效的登录用户,前提是您已正确配置其他所有内容。
我假设您已将控制器设置为使用属性 [Authorize] 属性并在 IServiceCollection 配置中启用授权内容?
推荐阅读
- sql - 获取按值分组的 Sum 和 Percent WHERE 数据的查询
- python - 如何使用 OpenCV Python 和 GStreamer 后端创建 x264 RTSP 服务器
- terraform - 找不到所需的 terraform 最低版本
- docusignapi - 如何从 DocuSign 帐户中查找帐户 ID?
- react-native - 如何从标签栏中删除屏幕名称
- node.js - 将我的应用程序部署到 Heroku 会出现错误 app[web.1]: node ERR! 这可能不是 Node.js 的问题
- spring - 无法写入请求:没有找到适合使用 Feign 的请求类型的 HttpMessageConverter
- makefile - CLion makefile error : Error running 'Makefile': Cannot run program "\usr\bin\make" CreateProcess error=2, 系统找不到指定的文件
- redirect - 从 Microsoft Office 中的链接重定向到 Auth0 失败
- python - Python:如何拆分文件中的每一行代码并添加到字典中