【问题标题】:Accessing and using UserClaims in ASP.NET Core Web API在 ASP.NET Core Web API 中访问和使用 UserClaims
【发布时间】:2020-08-07 19:48:39
【问题描述】:

我是第一次使用 ASP.NET Core Web API 并且对它很陌生。 我添加了声明,现在我想“阅读”并访问它们。

有人可以帮我吗?

【问题讨论】:

  • 您使用的是 JWT 还是 cookie 身份验证类型?还是什么?
  • @Mateech 我正在使用 JWT
  • 您需要在哪里访问 UserClaim?请求到来还是生成令牌?
  • 我需要使用 var Id = _userManager.GetUserId() 其中 GetUserId() 采用 ClaimsPrinicpal 实例。如果添加了声明,我该如何检索? @HoàngMinhThông
  • ms 文档你试过了吗?

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


【解决方案1】:

其实很简单。创建 JWT 令牌时,您会向其添加声明。它可以是 userId,他的角色等。

因此,当您设置使用 Bearer 方案授权时,每个需要授权的请求都将得到验证。例如,仅允许使用具有 claim-type role of admin 的 jwt 令牌访问此方法:

[Authorize(AuthenticationSchemes = "Bearer")]
public class YourController : ControllerBase
{
    ...
    [HttpGet]
    [Authorize(Roles = "admin")]
    public async Task<IActionResult> Method(string id)
    {
    }
    ...
}

如果令牌不需要声明,您将收到403 Forbidden 响应

【讨论】:

  • 我有点困惑。我需要使用 var Id = _userManager.GetUserId() 其中 GetUserId() 采用 ClaimsPrinicpal 实例。如果添加了声明,我该如何检索?
  • @Mansi 在您的控制器中,您可以通过这种方式更轻松地实现它:User.FindFirstValue(ClaimTypes.NameIdentifier) 或其他 ClaimTypes,如电子邮件等。
  • 我会试试这个!谢谢@Mateech
  • 我使用了 User.FindFirstValue(ClaimTypes.NameIdentifier) 和 HttpContextAccessor 依赖注入,它对我有用,谢谢 :)
猜你喜欢
  • 2019-04-18
  • 2021-06-26
  • 2018-11-12
  • 1970-01-01
  • 2017-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-24
相关资源
最近更新 更多