【问题标题】:ASP .NET CORE 2.2 JWT & Claims identity Authentication for WebsiteASP .NET CORE 2.2 JWT 和声明网站的身份验证
【发布时间】:2019-09-01 20:17:09
【问题描述】:

我有一个 .net core 2.2 api,它生成(在成功登录时)一个 JWT 令牌,其中包含一个声明身份,该身份传递信息,例如经过身份验证的用户的用户名、权限和角色。

在我的 .net 核心 2.2 中。 Web 应用程序我有一个登录机制,它通过控制器的用户检索 JWT 令牌。

我的问题是。

如何从我的登录控制器中扩展令牌并设置我的 Web 应用程序以包括使用身份验证机制(如 User.Identity.IsAuthenticatedUser.IsInRole("Admin"))和控制器操作(如 [Authorize][Authorize(Roles="Admin")]

我一直致力于查看 facebook/google 等外部身份验证提供程序背后的源代码,但无济于事。

提前致谢。

【问题讨论】:

  • 您是否已经设法在身份验证中间件中从您的 JWT 获取 IdentityUser ?您是否只是在寻找如何在控制器中处理授权?
  • 这就是我所追求的。那么你会推荐在我的启动类中引入一些身份验证中间件来创建身份用户吗?除了在控制器上授权用户之外,我还需要设置 User.Identity.IsAuthenticated 和 User.IsInRole("Admin") 变量来根据用户更改我的 UI。 @Skrface
  • 嗨..您使用的是identityserver4还是什么技术?
  • @federicoscamuzzi 我只是想使用 cookieauthentication、claimidentity 和 jwt

标签: c# asp.net-core .net-core jwt claims-based-identity


【解决方案1】:

第一步是在Startup.cs中使用cookie authentication

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

Configure 方法中,使用UseAuthentication 方法调用设置HttpContext.User 属性的身份验证中间件。在调用UseMvcWithDefaultRouteUseMvc之前调用UseAuthentication方法:

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.IsAuthenticatedUser.IsInRole("Admin")[Authorize(Roles="Admin")]

[Authorize(Roles = "Admin")]
public IActionResult About()
{
    var result = User.IsInRole("Admin");
    return View();
}

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 2017-09-11
    • 2019-09-06
    • 2018-07-03
    • 2019-12-24
    • 2021-06-15
    • 2020-05-30
    • 2019-10-14
    • 2020-10-09
    相关资源
    最近更新 更多