0

Hi I have a azure function where I'm trying to get the current id of the user from a jwt token.

I'm currently reading it from the header which makes sense to me but I'm concerned I may not be following best practices.

Also the first line seems a bit hacky to me.

Can you guys please take a look at it and suggest how I can improve this.

Or is this totally the wrong approach?

[FunctionName(nameof(GetDates))]
public static async Task<IActionResult> Run(

[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "dates")]HttpRequest req, ILogger logger, [Table("Date")] CloudTable table

            )

        {

            var token = req.Headers["Authorization"][0].Replace("Bearer ", string.Empty);



            var handler = new JwtSecurityTokenHandler();

           var jtToken = handler.ReadJwtToken(token);



            var userId = jtToken.Payload["Id"].ToString();
CraftyFox
  • 165
  • 2
  • 11

1 Answers1

0

from your code seems you just read out the claim value from jwt token Payload but you have not authenticate the jwt token.

Generally , Jwt tokens composed by three pieces : Header,payload,signature.

Header - Provides information about how to validate the token including information about the type of token and how it was signed.

Payload - Contains all of the important data about the user or app that is attempting to call your service.

Signature - Is the raw material used to validate the token.

Each part is based64 encoded and be Split by "." in jwt, you can parse your jwt here to check its Header and Payload: https://jwt.io/

Signature is composed by header and payload content and signed with a private key of Identity provider(who issued this jwt).

If you want to verify the jwt, the work you should do is getting a public key from Identity provider and use this public key to unlock the signature part: you will get the cleartext value of Header and Payload. If the content of Header and Payload of jwt is totally same you unlocked from Signature part, this means this token is a validated one.

This is a post about how to verify a jwt from Azure AD , It think it will be helpful for you . If you have any further concerns , pls feel free to let me know.

Stanley Gong
  • 11,522
  • 1
  • 8
  • 16