【问题标题】:JWT Token Accessing AuthenticatedUserJWT Token 访问 AuthenticatedUser
【发布时间】:2021-03-10 01:20:31
【问题描述】:

我正在尝试从令牌访问用户 ID,但我尝试的所有操作都返回 null。生成的令牌有必要的信息,所以我认为不是令牌生成。

这是创建令牌的部分

        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(_jwtSettings.Secret);
        var tokenDescriptor = new SecurityTokenDescriptor()
        {
            Subject = new ClaimsIdentity(new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim(ClaimTypes.NameIdentifier, existingAppUser.Id),
                new Claim("id", existingAppUser.Id),
            }),
            Expires = DateTime.UtcNow.AddDays(7),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };

        var token = tokenHandler.CreateToken(tokenDescriptor);

        return new AuthenticationResult()
        {
            Token = tokenHandler.WriteToken(token)
        };

当我解码生成的令牌时,我可以看到令牌中的所有声明,但我无法在项目中访问它。

这是试图访问名称标识符或 id 声明的部分

        var claimsList = _httpContextAccessor.HttpContext.User.Claims.ToList();

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

        var nameId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;

        var id = _httpContextAccessor.HttpContext.User.FindFirst(x => x.Type == "id")?.Value;

这是启动时的 JWT 配置

services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
            .AddJwtBearer(x =>
            {
                x.SaveToken = true;
                x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuerSigningKey = false,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret)),
                    ValidateAudience = false,
                    ValidateLifetime = true,
                    ValidateIssuer = false
                };
            });

        services.AddAuthorization();
        services.AddHttpContextAccessor();

这是我试图从中访问它的类

    public class CurrentUserService : ICurrentUserService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public CurrentUserService( IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public string UserId { get => _httpContextAccessor.HttpContext.User.Claims.Single(x => x.Type == "id").Value; }

    public string GetUserId()
    {
        var claimsList = _httpContextAccessor.HttpContext.User.Claims.ToList();

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

        var nameId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;

        var id = _httpContextAccessor.HttpContext.User.FindFirst(x => x.Type == "id")?.Value;

        return "123";
    }
}

我不知道我在这里缺少什么。如何从令牌中获取 userId?

【问题讨论】:

  • 请在启动时包含 JWT 配置。除了 JWT 之外,你是否配置了其他授权方案?您究竟从哪里访问HttpContext?如果授权成功,需要 JWT 授权的控制器操作应包含身份声明。
  • 我已添加您要求的文件。我正在尝试从服务访问它。

标签: c# asp.net asp.net-core jwt asp.net-core-3.1


【解决方案1】:

原来我忘记放了

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

在必要的控制器中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-13
    • 2018-06-21
    • 2019-10-18
    • 2021-08-14
    • 2021-10-12
    • 2015-11-10
    • 1970-01-01
    • 2021-04-16
    相关资源
    最近更新 更多