Created
March 2, 2023 11:10
-
-
Save tostrowski/0f1963d689ea0c4b669cc4ae6f7cd328 to your computer and use it in GitHub Desktop.
Local JWT decoder.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.govisdom.flow.services.auth; | |
import java.nio.charset.StandardCharsets; | |
import java.util.Base64; | |
import java.util.Map; | |
import java.util.stream.Collectors; | |
import com.auth0.jwt.exceptions.JWTDecodeException; | |
import com.auth0.jwt.impl.JWTParser; | |
import doublefin.auth.dto.JwtToken; | |
public class LocalJwtDecoder { | |
public static JwtToken decode(String jwt) { | |
JWTParser converter = new JWTParser(); | |
final var parts = splitToken(jwt); | |
String headerJson; | |
String payloadJson; | |
try { | |
headerJson = new String(Base64.getUrlDecoder().decode(parts[0]), StandardCharsets.UTF_8); | |
payloadJson = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); | |
} catch (NullPointerException e) { | |
throw new JWTDecodeException("The UTF-8 Charset isn't initialized.", e); | |
} catch (IllegalArgumentException e) { | |
throw new JWTDecodeException("The input is not a valid base 64 encoded string.", e); | |
} | |
final var header = converter.parseHeader(headerJson); | |
final var payload = converter.parsePayload(payloadJson); | |
final var claims = payload.getClaims().entrySet().stream() | |
.collect(Collectors.toMap(Map.Entry::getKey, (e) -> e.getKey().equals("exp") ? Long.toString(e.getValue().asLong()) : e.getValue().asString())); | |
return new JwtToken("API", payload.getExpiresAt(), payload.getSubject(), claims); | |
} | |
private static String[] splitToken(String token) throws JWTDecodeException { | |
String[] parts = token.split("\\."); | |
if (parts.length == 2 && token.endsWith(".")) { | |
//Tokens with alg='none' have empty String as Signature. | |
parts = new String[]{parts[0], parts[1], ""}; | |
} | |
if (parts.length != 3) { | |
throw new JWTDecodeException( | |
String.format("The token was expected to have 3 parts, but got %s.", parts.length)); | |
} | |
return parts; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment