问题:
When I try to parse header from jwt as base64 to string then the output is :
{"alg":"RS256","typ":"JWT","kid":"1234"
without last bracket, but when I decode the...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
When I try to parse header from jwt as base64 to string then the output is :
{"alg":"RS256","typ":"JWT","kid":"1234"
without last bracket, but when I decode the same base64 string for example here: https://www.base64decode.org/ then the json has correct format.
function that I use:
public void test() {
String encodedToken = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMzQifQ";
System.out.println(new String(DatatypeConverter.parseBase64Binary(encodedToken)));
}
What can be wrong?
EDIT: Java 7 is mandatory.
回答1:
Try to encode {"alg":"RS256","typ":"JWT","kid":"1234"}
in base64
You will see eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMzQifQ==
==
- is a padding
I think that problem is DatatypeConverter.parseBase64Binary
use representation of xsd:base64Binary (RFC 2045). But in RFC 2045 padding is mandatory.
You can use this way (java.util.Base64):
public void test() {
String encodedToken = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMzQifQ";
System.out.println(new String(Base64.getDecoder().decode(encodedToken.getBytes())));
}
java.util.Base64 uses RFC 4648 (padding is optional).
回答2:
and welcome on StackOverflow. According to this answer on Github, DatatypeConverter.parseBase64Binary()
has some bugs and doesn't output the correct decoded string.
If you're using Java 8 or higher you can decode this way:
String base64 = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMzQifQ";
byte[] temp = Base64.getDecoder().decode(base64.getBytes());
System.out.println(new String(temp));
importing class java.util.Base64