Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

After implementing jwt I always got HttpContext.User is null #1031

Closed
salmanshafiq00 opened this issue Oct 24, 2023 · 5 comments
Closed

After implementing jwt I always got HttpContext.User is null #1031

salmanshafiq00 opened this issue Oct 24, 2023 · 5 comments

Comments

@salmanshafiq00
Copy link

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.

image

Unfortunately, I got null from HttpContext's User.

image

Here, is my CurrentUser service for getting the current user

image

I tried a lot can't find any solutions. I have nothing what should to do. pls help.

@ramax495
Copy link
Contributor

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"

@salmanshafiq00
Copy link
Author

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
image

Little bit change in CurrentUser class
image

still, user of httpcontext shows null
image

is there any possibility that when i request with Bearer token, the action can't verify bearer token?

but i get the bearer token in request header.
image

@iamcymentho
Copy link

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!

@Chris-Mingay
Copy link

Chris-Mingay commented Nov 5, 2023

@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

@salmanshafiq00
Copy link
Author

@iamcymentho @Chris-Mingay ,
For your concern I push my repo in GitHub and here is the link https://github.com/salmanshafiq00/LMS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants