简体   繁体   English

如何在Azure函数中对JWT令牌进行身份验证

[英]How to authenticate jwt token in azure function

Hi I have a azure function where I'm trying to get the current id of the user from a jwt token. 嗨,我有一个azure函数,我试图从jwt令牌中获取用户的当前ID。

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();

from your code seems you just read out the claim value from jwt token Payload but you have not authenticate the jwt token. 从您的代码中看来,您只是从jwt令牌有效负载中读取了索赔值,但尚未验证jwt令牌。

Generally , Jwt tokens composed by three pieces : Header,payload,signature. 通常,Jwt令牌由三部分组成:标头,有效载荷,签名。

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 "." 每个部分都基于64编码,并用“。”分隔。 in jwt, you can parse your jwt here to check its Header and Payload: https://jwt.io/ 在jwt中,您可以在此处解析jwt以检查其Header和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). 签名由标头和有效内容组成,并用身份提供者(由其发行此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. 如果要验证jwt,您应该做的工作是从身份提供者那里获取公共密钥,并使用该公共密钥来解锁签名部分:您将获得Header和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. 如果jwt的Header和Payload的内容与您从Signature部分解锁的内容完全相同,则意味着此令牌是经过验证的令牌。

This is a post about how to verify a jwt from Azure AD , It think it will be helpful for you . 这是有关如何从Azure AD验证jwt的文章 ,它认为它将对您有所帮助。 If you have any further concerns , pls feel free to let me know. 如果您还有其他疑问,请随时告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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