我正在用Blazor编写客户端应用程序,它可以访问JWT。我想知道一种简单的方法来读取令牌有效负载内容,而不添加额外的依赖项,因为我不需要其他信息,也不需要验证令牌。我认为解析有效负载内容应该足够简单,只需在一个方法中编写即可。
JwtTokenContent ReadJwtTokenContent(string token)
{
var content = token.Split('.')[1];
// Exception here, it's not a valid base64 string
var jsonPayload = Encoding.UTF8.GetString(
Convert.FromBase64String(content));
Console.WriteLine(jsonPayload);
return JsonSerializer.Deserialize<JwtTokenContent>(jsonPayload);
}
如何解码有效载荷?它似乎不仅仅是一个base64字符串。
输入不是有效的Base-64字符串,因为它包含非Base-64字符、两个以上的填充字符或填充字符中的非法字符。
这是一个JWT令牌示例:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJJZCI6IjUyYjg3ZTUwLTViYmMTNDE0NyiOTMwLWY2ZGI0ZTUyndewYiIsIlVzZXJuYW1iJoiZGF0dm1Ab3V0bG9vay5jb20iLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo0NDMyMi8ifQ.4wKxDCwQ6onvNA_atndSitGjufR-tXutWq-tRNhKzc
(内容为eyJJZCI6IjUyYjg3ZTUwLTViYmMtNDE0Ny1iOTMwLWY2ZGI0ZTUyNDEwYiIsIlVzZXJuYW1lIjoiZGF0dm1Ab3V0bG9vay5jb20iLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo0NDMyMi8ifQ
(
感谢Kalten,这是我的案例的解决方案:
JwtTokenContent ReadJwtTokenContent(string token)
{
var content = token.Split('.')[1];
Console.WriteLine(content);
var jsonPayload = Encoding.UTF8.GetString(
this.Decode(content));
Console.WriteLine(jsonPayload);
return JsonSerializer.Deserialize<JwtTokenContent>(jsonPayload);
}
byte[] Decode(string input)
{
var output = input;
output = output.Replace('-', '+'); // 62nd char of encoding
output = output.Replace('_', '/'); // 63rd char of encoding
switch (output.Length % 4) // Pad with trailing '='s
{
case 0: break; // No pad chars in this case
case 2: output += "=="; break; // Two pad chars
case 3: output += "="; break; // One pad char
default: throw new System.ArgumentOutOfRangeException("input", "Illegal base64url string!");
}
var converted = Convert.FromBase64String(output); // Standard base64 decoder
return converted;
}
试试Steve Anderson 的这个
public static IEnumerable<Claim> ParseClaimsFromJwt(string jwt)
{
var payload = jwt.Split('.')[1];
var jsonBytes = ParseBase64WithoutPadding(payload);
var keyValuePairs = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonBytes);
return keyValuePairs.Select(kvp => new Claim(kvp.Key, kvp.Value.ToString()));
}
private static byte[] ParseBase64WithoutPadding(string base64)
{
switch (base64.Length % 4)
{
case 2: base64 += "=="; break;
case 3: base64 += "="; break;
}
return Convert.FromBase64String(base64);
}
用法
var token = await GetTokenAsync();
var identity = string.IsNullOrEmpty(token)
? new ClaimsIdentity()
: new ClaimsIdentity(ServiceExtensions.ParseClaimsFromJwt(token), "jwt");