gpt4 book ai didi

c# - JWT Token 访问 AuthenticatedUser

转载 作者:行者123 更新时间:2023-12-03 17:08:13 25 4
gpt4 key购买 nike

我正在尝试从 token 访问用户 ID,但我尝试的所有内容都返回 null。生成的 token 具有必要的信息,所以我认为它不是 token 生成。
这是创建 token 的部分

        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)
};
当我解码生成的 token 时,我可以看到 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";
}
}
我不知道我在这里缺少什么。如何从 token 中获取 userId?

最佳答案

好吧,原来我忘了放

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
在必要的 Controller 中。

关于c# - JWT Token 访问 AuthenticatedUser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65034279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com