Skip navigation links

Oracle Fusion Middleware REST Security Java API Reference for Oracle Security Developer Tools
11g Release 1 (11.1.1)

E26380-02


oracle.security.restsec.jwt
Class JwtToken

java.lang.Object
  extended by oracle.security.restsec.jwt.JwtToken

All Implemented Interfaces:
oracle.security.crypto.token.Token

public class JwtToken
extends java.lang.Object
implements oracle.security.crypto.token.Token

This Class represents the JSON Web Token (JWT). The claims in a JWT are encoded as a JSON object that is digitally signed using a JSON Web Signature (JWS) and optionally encrypted using JSON Web Encryption (JWE). (See specification for details.)

JWT token contains three Segments: the JWT Header Segment, the JWT Claim Segment, and the JWT Crypto Segment, in that order, with the segments being separated by period ('.') characters. All the three Segments are always Base64url encoded values.

To build a JWT token, begin by using the constructor method JwtToken() to create a JwtToken object. Continue by using the various setter methods to set the parameter values of the JWT token. To get the Base64url representation of the JWT token use signAndSerialize(PrivateKey) or signAndSerialize(byte[]). One can use the method serializeUnsigned(), if the JWT token is not required to be digitally signed.

The value of the header parameter alg is MUST. Use the method setAlgorithm(String) to set the value of the header parameter alg. The default value of alg is "none". The following table shows the header parameter names and the corresponding methods to set/get their values.

Header parameter name JSON value type Provided methods to set/get the value of the header
alg string setAlgorithm(String), getAlgorithm()
typ string setType(String), getType()
jku string setJsonKeyURL(URL), getJsonKeyURL()
kid string setKeyID(String), getKeyID()
x5u string setX509URL(URL), getX509URL()
x5t string setX509CertThumbprint(X509Certificate), getX509CertThumbprint()

The value of the header parameters typ,jku, kid, x5u, x5t are case sensitive and optional.

To set user defined header parameter in the JWT Header Segment use the method setHeaderParameter(String, Object)

The value of the claim parameters exp, iat, iss, aud, prn are case sensitive and optional. The following table shows the claim parameter names and the corresponding methods to set/get their values.

Claim parameter name JSON value type Provided methods to set/get the value of the claim
exp integer setExpiryTime(Date), getExpiryTime()
iat integer setIssueTime(Date), getIssueTime()
iss string setIssuer(String), getIssuer()
aud string setAudience(String), getAudience()
prn string setPrincipal(String), getPrincipal()

To set user defined claim parameter in the JWT Claim Segment use the method setClaimParameter(String, Object)

To parse and verify the JWT token, create the instance of the JwtToken class using the constructor JwtToken(String). Use various getter methods to access the values of the different parameters. Use verify(byte[]) or verify(PublicKey) to verify the JWT token.

Example code for JWT token signing:-

JwtToken jwtToken = new JwtToken();
//Fill in all the parameters- algorithm, issuer, expiry time, other claims etc
jwtToken.setAlgorithm(JwtToken.SIGN_ALGORITHM.HS256.toString());
jwtToken.setType(JwtToken.JWT);
jwtToken.setIssuer("my.oracle.com");
jwtToken.setPrincipal("john.doe");

// Get the private key and sign the token with a secret key or a private key
PrivateKey privateKey ;
String jwtString = jwtToken.signAndSerialize(privateKey);

Example code for JWT token serialization without signing:-

JwtToken jwtToken = new JwtToken();
jwtToken.setType(JwtToken.JWT);
jwtToken.setIssuer("my.oracle.com");
jwtToken.setPrincipal("john.doe");

String jwtString = jwtToken.serializeUnsigned();

Example code to verify JWT token:-

// Read the JWT token as a String from HTTP header
String jwtStr = "eyJ.eyJp.dB";
JwtToken token = new JwtToken(jwtStr);

// Validate the issued and expiry time stamp.
if (token.getExpiryTime().after(new Date())) {
...
...
}

// Get the issuer from the token
String issuer = token.getIssuer();

// One need to maintain the mapping of issuer and issuer public key(i.e. a certificate)/secret key. Retrieve the issuer key from this map. It can be a secret key or a public key
PublicKey issuerKey = issuerKeyMap.get(issuer) ;
// Use this issuer key and verify the token.
boolean result = token.verify(issuerKey);

Working example code to sign JWT token (using HMAC SHA 256 algorithm):-

 static final byte[] hmacKey = { 3, 35, 53, 75, 43, 15, (byte) 165,
         (byte) 188, (byte) 131, 126, 6, 101, 119, 123, (byte) 166, (byte) 143,
         90, (byte) 179, 40, (byte) 230, (byte) 240, 84, (byte) 201, 40,
         (byte) 169, 15, (byte) 132, (byte) 178, (byte) 210, 80, 46, (byte) 191,
         (byte) 211, (byte) 251, 90, (byte) 146, (byte) 210, 6, 71, (byte) 239,
         (byte) 150, (byte) 138, (byte) 180, (byte) 195, 119, 98, 61, 34, 61,
         46, 33, 114, 5, 46, 79, 8, (byte) 192, (byte) 205, (byte) 154,
         (byte) 245, 103, (byte) 208, (byte) 128, (byte) 163 };
 
         JwtToken jwtToken = new JwtToken();
         jwtToken.setIssuer("joe");
         jwtToken.setExpiryTime(new Date(1300819380));
         jwtToken.setClaimParameter(http://example.com/is_root, true);
         jwtToken.setType(JwtToken.JWT);
         jwtToken.setAlgorithm(JwtToken.SIGN_ALGORITHM.HS256.toString());
         String jwtString = jwtToken.signAndSerialize(hmacKey);
         System.out.println(jwtString);
 
 The output for the above code will be:-
 "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
 .eyJleHAiOjEzMDA4MTkzODAsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlLCJpc3MiOiJqb2UifQ
 .tu77b1J0ZCHMDd3tWZm36iolxZtBRaArSrtayOBDO34";
 

Working example code to verify JWT token (using HMAC SHA 256 algorithm):-

         String jwtString = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9" +
         ".eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ" +
         ".dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
         
         JwtToken jwtToken = new JwtToken(jwtString);
         boolean result = jwtToken.verify(hmacKey);
         String algo = jwtToken.getAlgorithm();
         System.out.println("Type:- "+ jwtToken.getType());
         System.out.println("Issuer:- " + jwtToken.getIssuer());
         System.out.println("Expiry time:- " +jwtToken.getExpiryTime());
         Map<String, Object> claims = jwtToken.getClaimParameters();
         Map<String, Object> headers = jwtToken.getHeaderParameters();
         System.out.println("claims:- " + claims + "\n");
         System.out.println("headers:- " + headers + "\n");
          
         The output for the above code will be:-
         
         Type:- JWT
         Issuer:- joe
         Expiry time:- Thu Jan 15 17:20:19 PST 1970
         claims:- {iss=joe, exp=1300819380, http://example.com/is_root=true}
         headers:- {typ=JWT, alg=HS256}
 

Nested Class Summary
static class JwtToken.SIGN_ALGORITHM
           This represents the specific cryptographic algorithms to sign the contents of the JWT token.

 

Field Summary
static java.lang.String JWT
           This string constant represents the standard JWT token type
static java.lang.String JWT_URI
           This string constant represents the standard JWT token type uri

 

Constructor Summary
JwtToken()
           This constructor is used to build the JWT token.
JwtToken(java.lang.String jwtString)
           This constructor is used when Base64url encoded JWT token is required to be parsed in to JwtToken Class instance.

 

Method Summary
static byte[] fromBase64url(java.lang.String s)
          Returns the decoded form of the given Base64url encoded string.
 java.lang.String getAlgorithm()
           This method returns the cryptographic algorithm used to secure the JWS.
 java.lang.String getAudience()
          This method returns the intended audience for this JWT token.
 java.lang.Object getClaimParameter(java.lang.String claim)
          This method returns the value of the JWT claim.
 java.util.Map<java.lang.String,java.lang.Object> getClaimParameters()
          This method returns the map of the name/value pair of the JWT claim segment.
 java.util.Date getExpiryTime()
           This method returns the expiration time of the JWT token.
 java.lang.Object getHeaderParameter(java.lang.String header)
          This method returns the value of the JWT header.
 java.util.Map<java.lang.String,java.lang.Object> getHeaderParameters()
          This method returns the map of the name/value pair of the JWT header segment.
 java.lang.String getIssuer()
           This method returns the issuer of the JWT token.
 java.util.Date getIssueTime()
           This method returns the issue time of the JWT token.
 java.net.URL getJsonKeyURL()
           This method returns the URL that points to JSON-encoded public keys that can be used to validate the signature.
 java.lang.String getKeyID()
           This method returns the key id.
 java.lang.String getPrincipal()
           This method returns the principal of the JWT token.
 java.lang.String getType()
           This method returns the type of the JWT token.
 byte[] getX509CertThumbprint()
           This method returns the Base64url encoded SHA-1 thumbprint of the X.509 certificate, which can be used to validate the JWT signature.
 java.net.URL getX509URL()
           This method returns the URL pointing to the X.509 public key certificate or certificate chain that can be used to validate the signature.
 java.lang.String serializeUnsigned()
           This method is used to get the Base64url representation of the JWT token without any digital signature.
 void setAlgorithm(java.lang.String algorithm)
           This method sets cryptographic algorithm used to secure the JWS.
 void setAudience(java.lang.String audience)
           This method sets the aud claim in the JWT claim segment.
 void setClaimParameter(java.lang.String claimParameter, java.lang.Object value)
           This method is used to set the custom claims in the JWT claim segment.
 void setExpiryTime(java.util.Date expiryTime)
           This method sets the exp claim in the JWT claim segment.
 void setHeaderParameter(java.lang.String headerParameter, java.lang.Object value)
           This method is used to set the custom claims in the JWT header segment.
 void setIssuer(java.lang.String issuer)
           This method sets the iss claim in the JWT claim segment.
 void setIssueTime(java.util.Date issueTime)
           This method sets the iat claim in the JWT claim segment.
 void setJsonKeyURL(java.net.URL jsonKeyURL)
           This method sets the jku header parameter in the JWT header segment.
 void setKeyID(java.lang.String keyID)
           This method sets the kid header parameter in the JWT header segment.
 void setPrincipal(java.lang.String principal)
           This method sets the prn claim in the JWT claim segment.
 void setType(java.lang.String type)
           The value of the header parameter typ is case sensitive and optional, and if present the recommended values are either "JWT" or "http://openid.net/specs/jwt/1.0".
 void setX509CertThumbprint(java.security.cert.X509Certificate cert)
           This method sets the x5t header parameter in the JWT header segment.
 void setX509URL(java.net.URL x509url)
           This method sets the x5u header parameter in the JWT header segment.
 java.lang.String signAndSerialize(byte[] secret)
           This method returns the Base64url representation of the JWT token including the Crypto segment.
 java.lang.String signAndSerialize(java.security.PrivateKey privateKey)
           This method returns the Base64url representation of the JWT token including the Crypto segment.
static java.lang.String toBase64url(byte[] data)
          Returns the Base64url encoding of the given byte array.
 java.lang.String toString()
           This method returns the text representation of the name/value pair defined in the JWT token.
 boolean verify(byte[] secret)
           This method is used to verify the digitally signed JWT token.
 boolean verify(java.security.PublicKey publicKey)
           This method is used to verify the digitally signed JWT token.

 

Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

 

Field Detail

JWT

public static final java.lang.String JWT

This string constant represents the standard JWT token type

See Also:
Constant Field Values

JWT_URI

public static final java.lang.String JWT_URI

This string constant represents the standard JWT token type uri

See Also:
Constant Field Values

Constructor Detail

JwtToken

public JwtToken()

This constructor is used to build the JWT token. The default value of the header parameter alg is set to "none".


JwtToken

public JwtToken(java.lang.String jwtString)
         throws JwtException

This constructor is used when Base64url encoded JWT token is required to be parsed in to JwtToken Class instance.

Parameters:
jwtString - the Base64url encoded JWT token to be parsed
Throws:
JwtException - if some error occurs while deserialization of the JWT Base64url string

Method Detail

fromBase64url

public static byte[] fromBase64url(java.lang.String s)
Returns the decoded form of the given Base64url encoded string.
Parameters:
s - the string to be decoded.

toBase64url

public static java.lang.String toBase64url(byte[] data)
Returns the Base64url encoding of the given byte array. Removes any padding and replaces '+' with '-' and '/' with '_'.
Parameters:
data - the data to be encoded.

getAlgorithm

public java.lang.String getAlgorithm()

This method returns the cryptographic algorithm used to secure the JWS.

Returns:
the value of the header parameter "alg" in the JWT header segment

getAudience

public java.lang.String getAudience()
This method returns the intended audience for this JWT token.
Returns:
the value of the claim parameter "aud" in the JWT claim segment

getClaimParameter

public java.lang.Object getClaimParameter(java.lang.String claim)
This method returns the value of the JWT claim. The name of the claim is String and the value is a JSON Object. The simple data binding is used for processing JSON. Simple data binding means converting to and from Java Maps, Lists, Strings, Numbers, Booleans and nulls.
Parameters:
claim -
Returns:
the value of the JWT claim as an Object

getClaimParameters

public java.util.Map<java.lang.String,java.lang.Object> getClaimParameters()
This method returns the map of the name/value pair of the JWT claim segment. The name of the claim is String and the value is a JSON Object. The simple data binding is used for processing JSON. Simple data binding means converting to and from Java Maps, Lists, Strings, Numbers, Booleans and nulls.
Returns:
the map of the name/value pair of the JWT claim segment.

getExpiryTime

public java.util.Date getExpiryTime()

This method returns the expiration time of the JWT token.

Returns:
the value of the claim parameter "exp" as Date

getHeaderParameter

public java.lang.Object getHeaderParameter(java.lang.String header)
This method returns the value of the JWT header. The name of the header is String and the value is a JSON Object. The simple data binding is used for processing JSON. Simple data binding means converting to and from Java Maps, Lists, Strings, Numbers, Booleans and nulls.
Parameters:
header -
Returns:
the value of the JWT header as an Object

getHeaderParameters

public java.util.Map<java.lang.String,java.lang.Object> getHeaderParameters()
This method returns the map of the name/value pair of the JWT header segment. The name of the header is String and the value is a JSON Object.The simple data binding is used for processing JSON. Simple data binding means converting to and from Java Maps, Lists, Strings, Numbers, Booleans and nulls.
Returns:
the map of the name/value pair of the JWT header segment.

getIssuer

public java.lang.String getIssuer()

This method returns the issuer of the JWT token.

Returns:
the value of the claim parameter "iss" in the JWT claim segment

getIssueTime

public java.util.Date getIssueTime()

This method returns the issue time of the JWT token.

Returns:
the value of the claim parameter "iat" as Date

getJsonKeyURL

public java.net.URL getJsonKeyURL()
                           throws java.net.MalformedURLException

This method returns the URL that points to JSON-encoded public keys that can be used to validate the signature. The keys is encoded as per the JSON Web Key (JWK)

Returns:
the value of the header parameter "jku" in the JWT header segment as URL
Throws:
java.net.MalformedURLException - if the value of the parameter "jku" can not be converted in to a valid URL

getKeyID

public java.lang.String getKeyID()

This method returns the key id. It gives a pointer to a specific key owned by the signer, which should be used to validate the signature.

Returns:
the value of the header parameter "kid" in the JWT header segment

getPrincipal

public java.lang.String getPrincipal()

This method returns the principal of the JWT token.

Returns:
the value of the claim parameter "prn" in the JWT claim segment

getType

public java.lang.String getType()

This method returns the type of the JWT token.

Returns:
the value of the header parameter "typ" in the JWT header segment

getX509CertThumbprint

public byte[] getX509CertThumbprint()

This method returns the Base64url encoded SHA-1 thumbprint of the X.509 certificate, which can be used to validate the JWT signature.

Returns:
the value of the header parameter "x5t" in the JWT header segment as byte[]

getX509URL

public java.net.URL getX509URL()
                        throws java.net.MalformedURLException

This method returns the URL pointing to the X.509 public key certificate or certificate chain that can be used to validate the signature.

Returns:
the value of the header parameter "x5u" in the JWT header segment as URL
Throws:
java.net.MalformedURLException - if the value of the parameter "x5u" can not be converted in to a valid URL

serializeUnsigned

public java.lang.String serializeUnsigned()
                                   throws JwtException

This method is used to get the Base64url representation of the JWT token without any digital signature. The Crypto JWT segment of the unsigned JWT token will an EMPTY String.

Returns:
String the Base64url representation of the Unsigned JWT token
Throws:
JwtException

setAlgorithm

public void setAlgorithm(java.lang.String algorithm)

This method sets cryptographic algorithm used to secure the JWS.

Parameters:
algorithm - the algorithm to set.

The JSON Web Signature Reserved Algorithm Values are HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, ES512. The enum JwtToken.SIGN_ALGORITHM represents these values.

Algorithm Description
HS256 HMAC using SHA-256 hash algorithm
HS384 HMAC using SHA-384 hash algorithm
HS512 HMAC using SHA-512 hash algorithm2
RS256 RSA using SHA-256 hash algorithm
RS384 RSA using SHA-384 hash algorithm
RS512 RSA using SHA-512 hash algorithm
ES256 ECDSA using P-256 curve and SHA-256 hash algorithm
ES384 ECDSA using P-384 curve and SHA-384 hash algorithm
ES512 ECDSA using P-521 curve and SHA-512 hash algorithm
none The algorithm value "none", if the digital signature of JWT token is not required.
(See JSON Web Signature Reserved Algorithm Values for details).

setAudience

public void setAudience(java.lang.String audience)

This method sets the aud claim in the JWT claim segment. This claim identifies the audience that the JWT is intended for. The principal intended to process the JWT MUST be identified by the value of the audience claim.

Parameters:
audience - the audience to set

setClaimParameter

public void setClaimParameter(java.lang.String claimParameter,
                              java.lang.Object value)

This method is used to set the custom claims in the JWT claim segment. The name of the claim must be a String and the value of the claim must be a JSON Object. The simple data binding is used for processing JSON. Simple data binding means converting to and from Java Maps, Lists, Strings, Numbers, Booleans and nulls.

Parameters:
claim - the name of the claim parameter
value - the value of the claim parameter

setExpiryTime

public void setExpiryTime(java.util.Date expiryTime)

This method sets the exp claim in the JWT claim segment. This claim identifies the expiration time on or after which the token MUST NOT be accepted for processing.

Parameters:
expiryTime - the expiry time to set

setHeaderParameter

public void setHeaderParameter(java.lang.String headerParameter,
                               java.lang.Object value)

This method is used to set the custom claims in the JWT header segment. The name of the header must be a String and the value of the claim must be a JSON Object. The simple data binding is used for processing JSON. Simple data binding means converting to and from Java Maps, Lists, Strings, Numbers, Booleans and nulls.

Parameters:
headerParameter - the name of the header parameter
value - the value of the header parameter

setIssuer

public void setIssuer(java.lang.String issuer)

This method sets the iss claim in the JWT claim segment. This claim identifies the principal that issued the JWT.

Parameters:
issuer - the issuer to set

setIssueTime

public void setIssueTime(java.util.Date issueTime)

This method sets the iat claim in the JWT claim segment. This claim identifies the UTC time at which the JWT was issued.

Parameters:
issueTime - the issue time to set

setJsonKeyURL

public void setJsonKeyURL(java.net.URL jsonKeyURL)

This method sets the jku header parameter in the JWT header segment. This header parameter is a URL that points to JSON-encoded public keys that can be used to validate the signature. The keys MUST be encoded as per the JSON Web Key (JWK).

Parameters:
jsonKeyURL - the JSON key URL to set

setKeyID

public void setKeyID(java.lang.String keyID)

This method sets the kid header parameter in the JWT header segment. This header parameter value gives a pointer for a specific key owned by the signer, which should be used to validate the signature. This allows signers to explicitly signal a change of key to recipients.

Parameters:
keyID - the keyID to set

setPrincipal

public void setPrincipal(java.lang.String principal)

This method sets the prn claim in the JWT claim segment. This claim identifies to the principal for whom the access token is being requested.

Parameters:
audience - the principal to set

setType

public void setType(java.lang.String type)

The value of the header parameter typ is case sensitive and optional, and if present the recommended values are either "JWT" or "http://openid.net/specs/jwt/1.0". The String constants JWT and JWT_URI represents these values respectively.

Parameters:
type - the type of JWT token to set

setX509CertThumbprint

public void setX509CertThumbprint(java.security.cert.X509Certificate cert)
                           throws JwtException

This method sets the x5t header parameter in the JWT header segment. This header parameter identifies to a base64url encoded SHA-1 thumbprint of an X.509 certificate

Parameters:
x509CertThumbprint - the x509Certificate whose thumbprint is to be set
Throws:
JwtException

setX509URL

public void setX509URL(java.net.URL x509url)

This method sets the x5u header parameter in the JWT header segment. This header parameter corresponds to a URL that points to an X.509 public key certificate or certificate chain that can be used to validate the signature.

Parameters:
x509url - the x509URL to set

signAndSerialize

public java.lang.String signAndSerialize(byte[] secret)
                                  throws SigningException,
                                         JwtException

This method returns the Base64url representation of the JWT token including the Crypto segment. The following steps are followed:-

1. The signing input is created by the concatenation of the JWT header segment (Base64url), a period ('.') character, and JWT claim segment (Base64url).

2. The digital signature of the above signing input is computed using the provided key. The Crypto segment is the Base64url representation of the computed digital signature

3. The result of the signing of the JWT token will be the concatenation of the JWT header segment, a period ('.') character, JWT claim segment , a period ('.') character, and JWT Crypto segment.

Parameters:
secret - The MAC key or password to be used to compute the HMAC signature bytes
Returns:
String the Base64url representation of the signed JWT token
Throws:
SigningException
JwtException

signAndSerialize

public java.lang.String signAndSerialize(java.security.PrivateKey privateKey)
                                  throws SigningException,
                                         JwtException

This method returns the Base64url representation of the JWT token including the Crypto segment. The following steps are followed:-

1. The signing input is created by the concatenation of the JWT header segment (Base64url), a period ('.') character, and JWT claim segment (Base64url).

2. The digital signature of the above signing input is computed using the provided key. The Crypto segment is the Base64url representation of the computed digital signature

3. The result of the signing of the JWT token will be the concatenation of the JWT header segment, a period ('.') character, JWT claim segment , a period ('.') character, and JWT Crypto segment. *

Parameters:
privateKey - the key to be used to sign the JWT input
Returns:
String the Base64url representation of the signed JWT token
Throws:
SigningException
JwtException

toString

public java.lang.String toString()

This method returns the text representation of the name/value pair defined in the JWT token. First segment is the name/value pairs of the header segment and the second segment is the collection of the name/value pair of the claim segment.

Overrides:
toString in class java.lang.Object

verify

public boolean verify(byte[] secret)
               throws VerifyException

This method is used to verify the digitally signed JWT token. It does nothing, if the token is not signed (i.e., the crypto segment of the JWT token is an empty string).

Parameters:
secret - the secret to be used to verify the HMAC signature bytes of the JWT token
Returns:
true if the signature of the JWT token is valid
Throws:
VerifyException - if an error occurs while verifying the signature of the JWT token

verify

public boolean verify(java.security.PublicKey publicKey)
               throws VerifyException

This method is used to verify the digitally signed JWT token. No signature verification is done, if the token is not signed (i.e., the Crypto segment of the JWT token is an empty string), and the value of the header parameter alg is "none".

Parameters:
publicKey - the key to be used to verify the signature of the JWT token
Returns:
true if the signature of JWT token is successfully verified
Throws:
VerifyException - if some error occurs while verifying the signature of JWT token

Skip navigation links

Oracle Fusion Middleware REST Security Java API Reference for Oracle Security Developer Tools
11g Release 1 (11.1.1)

E26380-02


Copyright © 2011, 2013 , Oracle. All rights reserved.