c# - ASP .NET CORE 2.2 JWT 和声明网站的身份验证
问题描述
我有一个 .net core 2.2 api,它生成(在成功登录时)一个 JWT 令牌,其中包含一个声明身份,该身份传递信息,例如经过身份验证的用户的用户名、权限和角色。
在我的 .net 核心 2.2 中。Web 应用程序我有一个登录机制,它通过控制器的用户检索 JWT 令牌。
我的问题是。
如何从我的登录控制器中扩展令牌并设置我的 Web 应用程序以包括使用身份验证机制User.Identity.IsAuthenticated
,如和User.IsInRole("Admin")
控制器操作[Authorize]
[Authorize(Roles="Admin")]
我一直致力于查看 facebook/google 等外部身份验证提供程序背后的源代码,但无济于事。
提前致谢。
解决方案
第一步是cookie authentication
使用Startup.cs
:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
在该Configure
方法中,使用该UseAuthentication
方法调用设置 HttpContext.User 属性的身份验证中间件。UseMvcWithDefaultRoute
在调用or之前调用 UseAuthentication 方法UseMvc
:
app.UseAuthentication();
然后在您的身份验证控制器中,获取令牌并解码以获取声明后,您应该创建新的ClaimsIdentity
,添加您的声明并登录用户:
if (!User.Identity.IsAuthenticated)
{
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, YourName));
identity.AddClaim(new Claim(ClaimTypes.Name, YourName));
identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
//Add your custom claims
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true });
}
之后,您可以使用User.Identity.IsAuthenticated
和:User.IsInRole("Admin")
[Authorize(Roles="Admin")]
[Authorize(Roles = "Admin")]
public IActionResult About()
{
var result = User.IsInRole("Admin");
return View();
}
推荐阅读
- javascript - 从子挂载发出事件并从父挂载访问
- python - 将 Pandas DataFrame 转换为列表
- angular - 从 6.4.1 迁移后的 Angular 7.1 得到`Uncaught(in promise):错误:不存在具有 id:name 的控件`
- c++ - 理解类型转换(指针)
- javascript - 引导模式使屏幕变暗但不会显示
- node.js - Express 和 node 向车把视图发送错误消息
- python - 最pythonic的方式来透视这个数据
- sql - 根据字符数插入称呼
- python - 如何增加opencv中高半径值的椭圆弧分辨率?
- matplotlib - 将散点图的形状更改为 Julia PyPlot 图例中的一条线