/
CredentialsDecoder.java
73 lines (60 loc) · 2.61 KB
/
CredentialsDecoder.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package org.eclipse.jetty.security.openid;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.Map;
import org.eclipse.jetty.util.ajax.JSON;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/**
* Used to decode the ID Token from the base64 encrypted JSON Web Token (JWT).
*/
public class CredentialsDecoder
{
private static final Logger LOG = Log.getLogger(CredentialsDecoder.class);
private static final Base64.Decoder decoder = Base64.getUrlDecoder();
/**
* Decodes a JSON Web Token (JWT) into a Map of claims.
* @param jwt the JWT to decode.
* @return the map of claims encoded in the JWT.
*/
public static Map<String, Object> decode(String jwt)
{
if (LOG.isDebugEnabled())
LOG.debug("decode {}", jwt);
String[] sections = jwt.split("\\.");
if (sections.length != 3)
throw new IllegalArgumentException("JWT does not contain 3 sections");
String jwtHeaderString = new String(decoder.decode(padJWTSection(sections[0])), StandardCharsets.UTF_8);
String jwtClaimString = new String(decoder.decode(padJWTSection(sections[1])), StandardCharsets.UTF_8);
String jwtSignature = sections[2];
Map<String, Object> jwtHeader = (Map)JSON.parse(jwtHeaderString);
if (LOG.isDebugEnabled())
LOG.debug("JWT Header: {}", jwtHeader);
/* If the ID Token is received via direct communication between the Client
and the Token Endpoint (which it is in this flow), the TLS server validation
MAY be used to validate the issuer in place of checking the token signature. */
if (LOG.isDebugEnabled())
LOG.debug("JWT signature not validated {}", jwtSignature);
return (Map)JSON.parse(jwtClaimString);
}
static byte[] padJWTSection(String unpaddedEncodedJwtSection)
{
int length = unpaddedEncodedJwtSection.length();
int remainder = length % 4;
if (remainder == 1)
throw new IllegalArgumentException("Not a valid Base64-encoded string");
byte[] paddedEncodedJwtSection;
if (remainder > 0)
{
int paddingNeeded = (4 - remainder) % 4;
paddedEncodedJwtSection = Arrays.copyOf(unpaddedEncodedJwtSection.getBytes(), length + paddingNeeded);
Arrays.fill(paddedEncodedJwtSection, length, paddedEncodedJwtSection.length, (byte)'=');
}
else
{
paddedEncodedJwtSection = unpaddedEncodedJwtSection.getBytes();
}
return paddedEncodedJwtSection;
}
}