0

Am sending Bearer Token in the header from Postman. Now I need to get User Claim in the API using that bearer token. The code which I tried is not working means am not getting user Name/Email. How can I get user claim using Bearer Token?

public class RepositoryUserAccount : IRepositoryUserAccount
{
    private readonly HttpContext _httpContext;

    public RepositoryUserAccount(IHttpContextAccessor httpContextAccessor)
    {
        this._httpContext = httpContextAccessor.HttpContext;
    }

    public async Task EnableAuthenticator()
    {
        ClaimsPrincipal currentUser = _httpContext.User;
        var currentUserName = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
    }
}
Chandan Y S
  • 968
  • 11
  • 21

3 Answers3

1

You are registering it as a singleton as noted by your comment. Refactor this class to use the IHttpContextAccessor each time or change it to be a transitive dependency.

Heres the first method:

public class RepositoryUserAccount : IRepositoryUserAccount
{
    private readonly IHttpContextAccessor _httpContextAccessor;

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

    public async Task EnableAuthenticator()
    {
        ClaimsPrincipal currentUser = _httpContextAccessor.HttpContext.User;
        var currentUserName = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
    }
}
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

Let's assume the System.Security.Claims.ClaimTypes is Authentication

var claims = _httpContext.User.Claims.Where(x => x.Type == ClaimTypes.Authentication);
foreach (var claim in claims)
{
    var value = claim.Value; //<= the value of each claim
}
derodevil
  • 811
  • 1
  • 11
  • 37
0

What I did is, in startup I configured the services like,

var key = Encoding.ASCII.GetBytes(SECRET_KEY);
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

and in controller just I did like,

[HttpGet]
[Route("EnableAuthenticator")]
public void EnableAuthenticator()
{
   var user = HttpContext.User;
}

In user we will get all the claims. That's it!

Chandan Y S
  • 968
  • 11
  • 21