解析JWT中的字段
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20190722</version>
</dependency>private String getUsername(HttpHeaders requestHeaders){
String username = "";
if (filterUtils.getAuthToken(requestHeaders)!=null){
String authToken = filterUtils.getAuthToken(requestHeaders)
.replace("Bearer ","");
JSONObject jsonObj = decodeJWT(authToken);
try {
username = jsonObj.getString("preferred_username");
}catch(Exception e) {
logger.debug(e.getMessage());
}
}
return username;
}
private JSONObject decodeJWT(String JWTToken) {
String[] split_string = JWTToken.split("\\.");
String base64EncodedBody = split_string[1];
Base64 base64Url = new Base64(true);
String body = new String(base64Url.decode(base64EncodedBody));
JSONObject jsonObj = new JSONObject(body);
return jsonObj;
}Last updated