如何通过 C# 解码 JWT 令牌? [复制]

Posted

技术标签:

【中文标题】如何通过 C# 解码 JWT 令牌? [复制]【英文标题】:How to decode JWT token by C#? [duplicate] 【发布时间】:2021-01-10 07:17:48 【问题描述】:

我正在使用 .NET 5、ASP.NET Core 5 Web API 和 ASP.NET Core Identity。我有一个 JWT 令牌:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJFbWFpbCI6ImR1Y3R4QG1wc29sdXRpb25zLmlvIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvbmFtZWlkZW50aWZpZXIiOiJiM2E2ZTI5Zi1hZjdjLTRhZmUtYjA4Ni1jYmVjMjAzOTYxYmUiLCJleHAiOjE2MDE4ODk4OTksImlzcyI6Imh0dHA6Ly9tcHNvbHV0aW9ucy5pbyIsImF1ZCI6Imh0dHA6Ly9tcHNvbHV0aW9ucy5pbyJ9.0HmUptS8_VMPuYXMlSwfafhusiYPfyOPPaiSo6uSOMs

我需要获取电子邮件字符串foo@example.com。如何解码 JWT 令牌,然后在 C# 中获取电子邮件字符串?

【问题讨论】:

【参考方案1】:
using System.IdentityModel.Tokens;

// a sample jwt encoded token string which is supposed to be extracted from 'Authorization' HTTP header in your Web Api controller
var tokenString = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSJ9.eyJhdWQiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC8wMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJpYXQiOiIxNDI4MDM2NTM5IiwibmJmIjoiMTQyODAzNjUzOSIsImV4cCI6IjE0MjgwNDA0MzkiLCJ2ZXIiOiIxLjAiLCJ0aWQiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJhbXIiOiJwd2QiLCJvaWQiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJlbWFpbCI6Impkb2VAbGl2ZS5jb20iLCJwdWlkIjoiSm9obiBEb2UiLCJpZHAiOiJsaXZlLmNvbSIsImFsdHNlY2lkIjoiMTpsaXZlLmNvbTowMDAwMDAwMDAwMDAwMDAwIiwic3ViIjoieHh4eHh4eHh4eHh4eHh4eC15eXl5eSIsImdpdmVuX25hbWUiOiJKb2huIiwiZmFtaWx5X25hbWUiOiJEb2UiLCJuYW1lIjoiSm9obiBEb2UiLCJncm91cHMiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJ1bmlxdWVfbmFtZSI6ImxpdmUuY29tI2pkb2VAbGl2ZS5jb20iLCJhcHBpZCI6IjAwMDAwMDAwLTAwMDAtMDAwMC0wMDAwLTAwMDAwMDAwMDAwMCIsImFwcGlkYWNyIjoiMCIsInNjcCI6InVzZXJfaW1wZXJzb25hdGlvbiIsImFjciI6IjEifQ.K7BCa0NO-A5f9exFiWcIXFMGnLmmt3V2HVP0itMT-GsAxnQROWzJFDIQNFo4QhiW0NCCqJykVELeVBCy_7Dex2-szUPZ69rmmDVJhy_qkmAiHhS1mNZDvJ1sB-whb5wOJ_QPIlByVzubhTcNnuliTVjnTeuOurVJJcn0Vugx9UDkGgky0etHXzmKukWYp4nzA68Wf1xnzlMZBz7PfoPGhjgzQfceOkZJVXIBRMB_7tsyW7gYNbHB_aTiT47cEjkh-UdrZEdp2UaAKugC-es3m076kRHMJqx31x-zDLDBttKinRJVPctiqwb1jMOMV6cUAp2E6aMfEbNk_iqX_OKFJg";  

 // trim 'Bearer ' from the start since its just a prefix for the token string
var jwtEncodedString = tokenString.Substring(7);

var token = new JwtSecurityToken(jwtEncodedString: jwtEncodedString);
Console.WriteLine("email => " + token.Claims.First(c => c.Type == "Email").Value);

参考:https://gist.github.com/ptsurbeleu/4aa7851e2d8eaffec488

【讨论】:

以上是关于如何通过 C# 解码 JWT 令牌? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

在没有秘密的情况下解码 JWT 令牌

@auth0/angular-jwt : 从解码的令牌中获取声明

如何手动使 JWT 令牌过期?

如何从节点 api 中的获取请求中解码 JWT 令牌

如何在 Swift 中解码 JWT(JSON Web 令牌)令牌?

如何解码令牌并获取 Django 的 djangorestframework-jwt 包的信息