After implementing jwt I always got HttpContext.User is null
salmanshafiq00 opened this issue · comments
Describe the bug
I clone .net 7.0 project and implement jwt on this project. Also I used MS default Web API project instead SPA. After successful login and I tried to get data from another action which has authorize attribute. But unfortunately, I always found unauthorized even though it authorized request.
Here is my jwt provider class which in infrastructure layer.
public async Task GenerateJwtAsync(string userId)
{
var user = await _userManager.FindByIdAsync(userId);
var userRoles = await _userManager.GetRolesAsync(user);
var roleClaims = new List<Claim>();
foreach (var role in userRoles)
{
var identityRole = await _roleManager.FindByNameAsync(role);
roleClaims.AddRange(await _roleManager.GetClaimsAsync(identityRole));
}
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Id),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Email, user.Email),
new Claim("username", user.UserName),
new Claim("ip", GetIpAddress())
}
.Union(roleClaims);
var signingCredentials = new SigningCredentials(
new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_jwtOptions.SecretKey)),
SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
_jwtOptions.Issuer,
_jwtOptions.Audience,
claims,
null,
DateTime.Now.AddMinutes(_jwtOptions.DurationInMinutes),
signingCredentials
);
string tokenValue = new JwtSecurityTokenHandler().WriteToken(token);
return await Task.FromResult(tokenValue);
}
Here, is the dependency register in DependencyInjection classs.
Unfortunately, I got null from HttpContext's User.
Here, is my CurrentUser service for getting the current user
I tried a lot can't find any solutions. I have nothing what should to do. pls help.
Check values of claim constants.
When you create a token you use JwtRegisteredClaimNames.Sub
constant with value "sub"
.
And when you get claim in CurrentUser service you use ClaimTypes.NameIdentifier
and its value is "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"
NameIdentifier bind the Sub type value.
Also, more clearify, I added another Claim to jwt which is "uid" claim type.
Here, is my decoded token value in jwt
Little bit change in CurrentUser class
still, user of httpcontext shows null
is there any possibility that when i request with Bearer token, the action can't verify bearer token?
Hello @salmanshafiq00, your solution looks promising, and I'd like to investigate the null issue you encountered. Could you please push your implementation to the repository so that I can clone it and examine the code more closely? This will help me better understand the problem and assist with finding a resolution. Thank you!
@salmanshafiq00 I've been wrestling with similar in an effort to implement a more 'vanilla' JWT and I believe it's because the system isn't recognising your DefaultAuthenticationScheme and because of it, is not calling the [Authorize] attribute in the way you'd expect.
I believe you can decorate controllers with:
[Authorize(AuthenticationSchemes = "Bearer")]
I had thought I had set the authentication scheme in the way I set up identity but it doesn't seem to translate. I'll add more when/if
@iamcymentho @Chris-Mingay ,
For your concern I push my repo in GitHub and here is the link https://github.com/salmanshafiq00/LMS