Package com.bfo.json

Class JWT

java.lang.Object
com.bfo.json.JWT

public class JWT extends Object
A trivial JWT (Json Web Token) implementation Supports all signature algorithms supported by JWK.

Examples

 JWT jwt = new JWT(Json.parse("{....}"));
 SecretKey key = new JWK(bytearray, "HS256").getSecretKey();
 jwt.sign(key);                    // Sign using a symmetric key
 jwt = new JWT(jwt.toString());    // Encode then decode
 assert jwt.verify(key);           // Verify using the same symmetric key

 PublicKey pubkey = ...
 PrivateKey privkey = ...
 jwt.getHeader().put("x5u", ...);       // Add custom content to header
 jwt.sign(prikey);                      // Sign using a asymmetric key
 assert jwt.verify(pubkey);             // Verify using corresponding key

 jwt.getPayload().clear();              // Modify the payload
 assert !jwt.verify(pubkey);            // Signature is no longer valid

 assert jwt.isValidAt(jwt.getIssuedAt()); // check JWT time is not expired

 System.out.println(jwt.getPayload());
 System.out.println(jwt.getAlgorithm());
 
Since:
4
See Also:
  • Constructor Details

    • JWT

      public JWT()
      Create a new JWT with no payload and the "none" algorithm.
    • JWT

      public JWT(Json payload)
      Create a new JWT with the specified payload and the "none" algorithm.
      Parameters:
      payload - the payload object to embed in the JWT
    • JWT

      public JWT(CharSequence in)
      Create a new JWT from the encoded representation
      Parameters:
      in - the encoded JWT
      Throws:
      IllegalArgumentException - if the string is not a valid JWT
  • Method Details

    • setProvider

      public JWT setProvider(Provider provider)
      Set the Provider to be used for any cryptographic operations
      Parameters:
      provider - the crypto Provider to use, or null to use the default
      Returns:
      this
    • getProvider

      public Provider getProvider()
      Return the Provider set by setProvider(java.security.Provider)
      Returns:
      the provider
    • toString

      public String toString()
      Return the encoded JWT
      Overrides:
      toString in class Object
    • verify

      public boolean verify(Key key)
      Verify the JWT.
      Parameters:
      key - the key. A SecretKey, PublicKey, or null if the algorithm is "none". Missing keys or keys of the wrong type will cause this method to return false; specifically, if the algorithm is "none" the key must be null.
      Returns:
      true if the JWT is verified, false if it failed to verify.
      Throws:
      RuntimeException - wrapping a GeneralSecurityException if there are cryptographic problems when verifying.
    • sign

      public JWT sign(Key key)
      Sign the JWT. Sets the "alg" key in the header and updates the signature.
      Parameters:
      key - the key. A SecretKey or PrivateKey, or null if the algorithm is to be "none"
      Returns:
      this
      Throws:
      RuntimeException - wrapping a GeneralSecurityException if there are cryptographic problems when signing.
    • getAlgorithm

      public String getAlgorithm()
      Return the algorithm name.
      Returns:
      the algorithm name
    • getIssuedAt

      public long getIssuedAt()
      Return the issued at claim ("iat") in milliseconds since the epoch.
      Returns:
      the time or 0 if not set
      Since:
      5
    • getNotBefore

      public long getNotBefore()
      Return the not before claim ("nbf") in milliseconds since the epoch.
      Returns:
      the time or 0 if not set
      Since:
      5
    • getExpiry

      public long getExpiry()
      Return the expiry claim ("exp"), in milliseconds since the epoch.
      Returns:
      the time or 0 if not set
      Since:
      5
    • getIssuer

      public String getIssuer()
      Return the issuer claim ("iss")
      Returns:
      the issuer or null if not set
      Since:
      5
    • getSubject

      public String getSubject()
      Return the subject claim ("sub")
      Returns:
      the subject or null if not set
      Since:
      5
    • getAudience

      public List<String> getAudience()
      Return the audience claim ("aud")
      Returns:
      the audience claim, or an empty list if not set
      Since:
      5
    • getUniqueID

      public String getUniqueID()
      Return the unique id claim ("jti")
      Returns:
      the unique id or null if not set
      Since:
      5
    • setIssuedAt

      public void setIssuedAt(long ms)
      Set the issued at claim ("iat") in milliseconds since the epoch.
      Parameters:
      ms - the time, or 0 to unset it
      Since:
      5
    • setNotBefore

      public void setNotBefore(long ms)
      Set the not before claim ("nbf") in milliseconds since the epoch.
      Parameters:
      ms - the time, or 0 to unset it
      Since:
      5
    • setExpiry

      public void setExpiry(long ms)
      Set the expiry claim ("exp"), in milliseconds since the epoch.
      Parameters:
      ms - the time, or 0 to unset it
      Since:
      5
    • setIssuer

      public void setIssuer(String val)
      Set the issuer claim ("iss")
      Parameters:
      val - the issuer, or null to unset it
      Since:
      5
    • setSubject

      public void setSubject(String val)
      Set the subject claim ("sub")
      Parameters:
      val - the issuer, or null to unset it
      Since:
      5
    • setAudience

      public void setAudience(List<String> val)
      Set the audience claim ("aud")
      Parameters:
      val - the audience claim; null or an empty list will unset it
      Since:
      5
    • setUniqueID

      public void setUniqueID(String val)
      Set the unique id claim ("jti")
      Parameters:
      val - the unique id, or null to unset it
      Since:
      5
    • isValidAt

      public boolean isValidAt(long time)
      Check the token was valid at the specified time. If the supplied time is 0, the current time will be used. If the token has an expiry time and/or not-before time, they will be compared to the supplied time and false returned if they are out of range. If they are not specified, true is returned.
      Parameters:
      time - the token issued-at time, or 0 to use the current time
      Returns:
      if the key can not be determined as invalid at the specified time
    • getPayload

      public Json getPayload()
      Return the payload object. The sign(java.security.Key) method should be called after any modifications to the returned object to update the signature.
      Returns:
      the payload object
    • getHeader

      public Json getHeader()
      Return the header object. The sign(java.security.Key) method should be called after any modifications to the returned object to update the signature.
      Returns:
      the header object
    • getSignature

      public byte[] getSignature()
      Return the signature object. Any modifications to the returned object will invalidate the signature.
      Returns:
      the signature bytes, which will be zero-length if the algorithm is "none"