Alp*_*ğan 8 c# asp.net jwt asp.net-core asp.net-core-3.1
我正在尝试从令牌访问用户 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)
};
Run Code Online (Sandbox Code Playgroud)
当我解码生成的令牌时,我可以看到令牌中的所有声明,但我无法在项目中访问它。
这是尝试访问名称标识符或 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;
Run Code Online (Sandbox Code Playgroud)
这是启动时的 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();
Run Code Online (Sandbox Code Playgroud)
这是我试图从中访问它的课程
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";
}
}
Run Code Online (Sandbox Code Playgroud)
我不知道我在这里缺少什么。如何从令牌中获取 userId?
好吧,原来我忘了放
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
Run Code Online (Sandbox Code Playgroud)
在必要的控制器中。