简体   繁体   中英

Get User Id by JWT Token in ASP.NET Boilerplate

I added JWT Auth to my asp.net boilerplate project.

I try to get user identity (ideally will be Id) by Token

Here is how I try to do this.

[Authorize]
    [HttpGet]
    [ProducesResponseType(typeof(ShowJobDto), (int)System.Net.HttpStatusCode.OK)]
    public async Task<IActionResult> GetJobs(DateTime? from, DateTime? to)
    {
        var identity = (ClaimsIdentity)User.Identity;
        List<ShowJobDto> jobs;
        var query = _jobRepository.GetAllIncluding(x => x.WorkOrder.Quote,
            x => x.WorkOrder.Quote.Property.Addresses,
            x => x.Engineer).Where(x => x.JobStatus != JobStatus.Pending);
        if (from != null && to != null)
        {
            jobs = await query.Where(x => x.JobDate >= from).Where(x => x.JobDate <= to)
                .ProjectTo<ShowJobDto>(ObjectMapper).OrderBy(x => x.TimeFrom).ToListAsync();
            return Ok(jobs);
        }

        jobs = await query.ProjectTo<ShowJobDto>(ObjectMapper).OrderBy(x => x.TimeFrom).ToListAsync();
        return Ok(jobs);
    }

I postman I pass beare token like this

在此处输入图像描述

But when I set breakpoint here var identity = (ClaimsIdentity)User.Identity;

I got nothing. Where is my problem?

I'm using the following approach in order to Authorize users in one of my app. So I'm sure you can make some changes to this code and get what you need:

First you need to get the header and strip down the Bearer from it.

string authHeaderValue = Request.Headers["Authorization"];

Then you need to use ClaimsPrincipal to validate your Token which is part of System.Security.Claims

This is a simple presentation of it in a class:

public ClaimsPrincipal GetClaims(string token)
{
    var handler = new JwtSecurityTokenHandler();
    var validations = new TokenValidationParameters
    {
         ValidateIssuerSigningKey = true,
         IssuerSigningKey = SIGNING_KEY,
         ValidateIssuer = false,
         ValidateAudience = false
    };

    return handler.ValidateToken(token, validations, out var tokenSecure);
}

Note that ValidateToken is part of System.IdentityModel.Tokens.Jwt;

Here is how to strip down the Bearer from the token

var tokenClaims = GetClaims(authHeaderValue.Substring("Bearer ".Length).Trim());

Then you can look for user Identity or whatever you need in your Token:

var userId = tokenClaims.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).FirstOrDefault().Value;

In my case I stored userId in NameIdentifier. So change it according to your settings.

One more thing. Make sure that your Token isn't expired while you are testing your application.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM