【问题标题】:How to get user identity inside asp.net controller?如何在 asp.net 控制器中获取用户身份?
【发布时间】:2021-05-02 07:57:57
【问题描述】:

仅供参考:我已经看过这个答案,但答案无效 => How do I get current user in .NET Core Web API (from JWT Token)

场景
我有一个 ASP.net 5 Web API,几天前我从 ASP.net core 3.1 迁移了它。
我在后端设置了 JWT 身份验证。令牌发行工作正常。当我解码令牌时,每个声明都在那里。
我的前端调用后端中的端点。在控制器的这个端点内,我需要知道用户是谁。所以我想接收来自 JWT 令牌的声明。 如上所述,我已经尝试了上述几乎所有的解决方案,但都没有奏效。 所以我的问题是,控制器内的用户没有声明。

我目前的进度:
在 startup.cs 类中,我注册了 HttpContextAccessor。

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    ...
}

控制器:

namespace ...
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IConfiguration _config;
        private readonly IUserService _userService;
        private readonly IHttpContextAccessor _httpContextAccessor;

    public UserController(IConfiguration config, IUserService userService, IHttpContextAccessor httpContextAccessor)
    {
        _config = config;
        _userService = userService;
        _httpContextAccessor = httpContextAccessor;
    }

    [HttpGet("currentUser")]
    public IActionResult GetCurrentUser()
    {
        var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
        return Ok(userId);
    }

调用此端点后,我收到以下错误: System.NullReferenceException:“对象引用未设置为对象的实例。” 我猜依赖注入应该没问题。

User 内部的 Claims 属性是空的,所以我真的不知道如何解决这个问题。

【问题讨论】:

  • 您在令牌中看到了哪些声明?哪一个包含您希望检索的值?
  • @mason 我想使用电子邮件。但这不是一成不变的,我很灵活。我的最后一次尝试是使用 Nameidentifier,payload 中的键是“nameid”。
  • 你的 startup.cs 中有.AddOpenIdConnect() 吗?我能够对其进行映射,以便 HttpContext.User.Identity.Name 通过options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name" }; 从“名称”声明中获取其值,因此如果您将 NameClaimType 设置为“nameid”,它可能会起作用。
  • 我不完全明白你想在哪里调用 AddOpenIdConnect() 方法。 IServiceCollection 和 IApplicationBuilder 没有这个方法?
  • AddOpenIdConnect 将是您在 AuthenticationBuilder 上调用的扩展方法,例如 services.AddAuthentiction().AddOpenIdConnect()。但也许你正在使用不同的库。您应该从 Startup.cs 共享您的相关配置。 AddOpenIdConnect 方法来自Microsoft.AspNetCore.Authentication.OpenIdConnect 库。

标签: .net-core asp.net-core-webapi


【解决方案1】:

你可以试试这个:

         var username = _httpContextAccessor.HttpContext.User.Identity.Name;

关注official document了解更多信息。

【讨论】:

  • 这要求名称声明被成功映射。鉴于他们说 User 属性没有声明,我怀疑它是否已成功映射。
  • 是的@mason 是对的。我没有看到任何索赔。这个我也试过了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-18
  • 1970-01-01
  • 2018-09-30
  • 2010-11-19
  • 1970-01-01
  • 2013-11-09
相关资源
最近更新 更多