如何通过JwtSecurityTokenHandler获取JWT内嵌套自定义claim的子属性值
读取JWT嵌套自定义声明的解决方案
有两种常用的稳定实现方式:
方案1:JSON序列化反序列化(更推荐,兼容性强)
Microsoft.IdentityModel内部的JObject重写了ToString()方法,会直接输出对应结构的JSON字符串,你可以用自己项目中常用的JSON库(System.Text.Json或Newtonsoft.Json)解析即可,示例如下:
using System.Text.Json; var jwtTokenHandler = new JwtSecurityTokenHandler(); var decodedJwtToken = jwtTokenHandler.ReadJwtToken(encodedJwtToken); object customClaimObj = decodedJwtToken.Payload["my_custom_claim"]; // 转成JSON字符串后解析 string customClaimJson = customClaimObj.ToString(); // 方式A:直接用JsonNode解析,不需要提前定义类 JsonNode customClaimNode = JsonSerializer.Deserialize<JsonNode>(customClaimJson); string actValue = customClaimNode["act"].GetValue<string>(); // 可按需转成Guid Guid actGuid = Guid.Parse(actValue); // 方式B:定义强类型类解析,更适合业务场景规范使用 public class MyCustomClaim { public string Ctx { get; set; } public Guid Act { get; set; } } MyCustomClaim customClaim = JsonSerializer.Deserialize<MyCustomClaim>(customClaimJson); Guid actValue2 = customClaim.Act;
方案2:反射读取(性能更高,无需额外序列化开销)
如果不想做序列化转义,可以直接通过反射调用内部JObject的索引器读取属性:
var jwtTokenHandler = new JwtSecurityTokenHandler(); var decodedJwtToken = jwtTokenHandler.ReadJwtToken(encodedJwtToken); object customClaimObj = decodedJwtToken.Payload["my_custom_claim"]; // 反射调用内部JObject的字符串索引器获取act属性 var actValue = customClaimObj.GetType() .GetProperty("Item", new Type[] { typeof(string) }) .GetValue(customClaimObj, new object[] { "act" }) ?.ToString(); Guid actGuid = Guid.Parse(actValue);
内容的提问来源于stack exchange,提问作者Tobias
相关产品推荐
相关产品推荐

