Tag Archives: JWT

Producing JWT tokens

To produce the JWT token i’ll be using the Nimbus JOSE+JWT Java library, which implements the Javascript Object Signing and Encryption (JOSE) suite of specifications as well as the closely related JSON Web Token (JWT) specification.

Technologies used:

  • Apache Maven 3.0.5
  • Nimbus JOSE+JWT 2.16
  • Java 7

 

First, let’s add maven dependency for Nimbus JOSE+JWT lib:

<dependency>
    <groupId>com.nimbusds</groupId>
    <artifactId>nimbus-jose-jwt</artifactId>
    <version>2.16</version>
</dependency>

 

…and start composing the JWT reserved claims right away:

JWTClaimsSet jwtClaims = new JWTClaimsSet();
jwtClaims.setIssuer("https://my-auth-server.com");
jwtClaims.setSubject("Mariusz");
List aud = new ArrayList<>();
aud.add("https://my-web-app.com");
aud.add("https://your-web-app.com");
jwtClaims.setAudience(aud);
jwtClaims.setExpirationTime(new Date(new Date().getTime() + 1000*60*10));
jwtClaims.setNotBeforeTime(new Date());
jwtClaims.setIssueTime(new Date());
jwtClaims.setJWTID(UUID.randomUUID().toString());

as you can see, we’re setting up all of the Reserved Claim Names mentioned in my earlier post on JWT (ie. Issuer, Subject, Audience, Expiration Time (to 10 minutes), Not Before Time, Issued At Time and the JWT ID) and using random UUID as the identifier of the token.

 

When printed out the above, you should see something similar to this:

{
    "exp":1373625160,
    "sub":"Mariusz";,
    "nbf":1373624561,
    "aud":[
        "https:\/\/my-web-app.com",
        "https:\/\/your-web-app.com"
    ],
    "iss":"https:\/\/my-auth-server.com";,
    "jti":"c79772ea-8777-44dc-a0fe-9001aeee9d02",
    "iat":1373624561
}

 

now, let’s create the JWT header and specify RSA-OAEP as the encryption algorithm and 128-bit AES/GCM as the encryption method that will be used to protect the JWT token:

JWEHeader header = new JWEHeader(
    JWEAlgorithm.RSA_OAEP,
    EncryptionMethod.A128GCM
);

 

next create the EncryptedJWT object that will be later used to perform the RSA encryption:

EncryptedJWT jwt = new EncryptedJWT(header, jwtClaims);

 

…create an RSA encrypter with the specified public RSA key:

RSAEncrypter encrypter = new RSAEncrypter(publicRsaKey);

(for details on how to generate RSA keys, please read my post on “RSA Keys Generation”)

 

and do the actual encryption:

jwt.encrypt(encrypter);

 

finally, we can serialize to JWT compact form in order to print it out to the screen nicely:

String jwtString = jwt.serialize();

 

what you should see after performing the steps above, is something similar to this:

eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkExMjhHQ00ifQ.ZyVpnDsmei
R_krnjTvMkB7a-DJrgdvwzXsMImIUS6x7B3yLEH5igpfiGfMD79SqYW5P
Fd7PrXVvNhq4Gs0YSg8qPPlPCjmaW7OnR9Oi891PRL1PyF0HqGzJJacZI
uu_jbeY0MQ9Z3hzNcuivhak60YFWLlGQWA7l4e7tkX4Hs4.fKF7TxNXc_
TmDl_P.AEPF230Ib8AeioJ6A4Kg0YXbYjaO4O4LVBu6qHQN1BP7ri_jc5
uCcIe02oFNEXoJZnSlaZP84LOZcnloNX6JBrLQnDr90jxkeDcoyiiLoxC
nebYJIksqyvxsGOvsAMS7MUt1Ms3Ua7tBv5pft0YVvIY9CK0oPdEyCAiu
vBp6KOR4Y9xkTy1xev5SUcWQjmskUlqtLnsO7mXpsMI09xTq13FgM2fTS
C5MIXFx2un8n8esh_rFMIfTlqLky1oa7dvb28ICjbYZPEq4CpCOeeMcQC
KliSy6A.zUGNd9GHWAY0m_m7xrQOOg

 

Now, if you’d like to read the data back from the token using your private RSA key, you’d have to do the following:

parse the above JWT string using EncryptedJWT object:

EncryptedJWT jwt = EncryptedJWT.parse(jwtString);

 

create a decrypter with the specified private RSA key:

RSADecrypter decrypter = new RSADecrypter(privateRsaKey);

 

do the decryption:

jwt.decrypt(decrypter);

 

and print out the claims:

System.out.println("iss: " + jwt.getJWTClaimsSet().getIssuer());
System.out.println("sub: " + jwt.getJWTClaimsSet().getSubject());
System.out.println("aud: " + jwt.getJWTClaimsSet().getAudience().size());
System.out.println("exp: " + jwt.getJWTClaimsSet().getExpirationTime());
System.out.println("nbf: " + jwt.getJWTClaimsSet().getNotBeforeTime());
System.out.println("iat: " + jwt.getJWTClaimsSet().getIssueTime());
System.out.println("jti: " + jwt.getJWTClaimsSet().getJWTID());

 

resulting with the following output:

iss: https://my-auth-server.com
sub: Mariusz
aud: 2
exp: Fri Jul 12 12:32:40 CEST 2013
nbf: Fri Jul 12 12:22:41 CEST 2013
iat: Fri Jul 12 12:22:41 CEST 2013
jti: c79772ea-8777-44dc-a0fe-9001aeee9d02

 

 

If you’re interested in a complete source code of this example, please clone the following Gist available on my GitHub account.

 

 

 

Sources:

Advertisements

JWT (JSON Web Tokens)

While working on one of the security-related aspects of the platform i’m building, i came across JWT specification which i find very interesting and thought will share with you the notes i made while reading:

 

  1. JWT acronym stands for “JSON Web Tokens”.
  2. Definition of a security token:
    • encrypted data structure (in this case of JSON format) which contains:
      • information about the issuer and subject (claims)
      • proof of authenticity (digital signature)
      • expiration (validity) time
  1. Suggested pronunciation of JWT is the same as the English word “jot”.
  2. Basic facts:
  1. Why JSON-based standard?
    • XML-based SAML data format, exchanged over SOAP protocol offered a ton of encryption and signature options but was percieved as a “heavy” technology and of not much use by mobile appliance (initially not that strong in terms of computing power). JSON messages on the other hand don’t require a fairly advanced technology stack (like SAX, StAX, etc.) to produce and parse data structures and can be exchanged over HTTP (also, each browser nowadays is supporting JavaScript).
  1. Characteristics:
    • Plaintext JWTs: support use cases where the JWT content is secured by means other than a signature and/or encryption contained within the JWT. A plaintext JWT has the header “alg” parameter value set to “none”.
    • Encrypted JWTs: use JSON Web Signature (JWS) and JSON Web Encryption (JWE) to sign and/or encrypt the contents of the JWT using JSON Web Algorithms (JWA)
    • symmetric (HMACSHA256-384) and asymmetric (ECDSA, RSA) signatures
    • symmetric and asymmetric encryption (RSA, AES/CGM)
  1. Structure:
    • JWT Header
      • metadata
      • algorithms & keys used
    • JWT Claims
      • Reserved Claim Names:
        • “iss” (Issuer)
        • “sub” (Subject)
        • “aud” (Audience)
        • “exp” (Expiration)
        • “nbf” (Not Before)
        • “iat” (Issued At)
        • “jti” (JWT ID)
        • “typ” (Type)
      • Public Claim Names
      • Private Claim Names
  1. Example:
// header object
{
    "alg":"none"
}

// claims object
{
    "exp":1373625160,
    "sub":"Mariusz",
    "nbf":1373624561,
    "aud":[
        "https:\/\/my-web-app.com",
        "https:\/\/your-web-app.com"
    ],
    "iss":"https:\/\/my-auth-server.com",
    "jti":"c79772ea-8777-44dc-a0fe-9001aeee9d02",
    "iat":1373624561,

    // additional public claims
    "scope":["read", "search"],
    "client":"system A"

In the example above, the JWT Header implies that the encoded object is a Plaintext JWT. Additional public claims, may be useful for example in oAuth protocol (to know which system (A in this case) requested the token and what operations (read, search) will it be authorized to perform using this token).

  1. Sample encoding:
    • Base64url encoded representation of the JWT Header:
      • eyJhbGciOiJub25lIn0
    • Base64url encoded representation of the JWT Claims Set:
      • eyJleHAiOjEzNzM2NDI3NzYsInN1YiI6Ik1hcml1c3oiLCJuYmYiOjEzNzM2NDIxNzYsI
        mF1ZCI6WyJodHRwczpcL1wvbXktd2ViLWFwcC5jb20iLCJodHRwczpcL1wveW9
        1ci13ZWItYXBwLmNvbSJdLCJpc3MiOiJodHRwczpcL1wvbXktYXV0aC1zZXJ2ZXIu
        Y29tIiwianRpIjoiMWI2YjMxMTItMzkyZi00MzIxLTk2YjktNzkyYjhhMjcxOTliIiwiaWF
        0IjoxMzczNjQyMTc2fSwiY2xpZW50Ijoic3lzdGVtIEEiLCJzY29wZSI6WyJyZWFkIi
        wgInNlYXJjaCJd

 

Complete JWT is a result of concatenating encoded representations of the header and the claims set with a period (‘.’) character between the parts:

  • eyJhbGciOiJub25lIn0.eyJleHAiOjEzNzM2NDI3NzYsInN1YiI6Ik1hcml1c3oiLCJuYm
    YiOjEzNzM2NDIxNzYsImF1ZCI6WyJodHRwczpcL1wvbXktd2ViLWFwcC5jb20iLCJ
    odHRwczpcL1wveW91ci13ZWItYXBwLmNvbSJdLCJpc3MiOiJodHRwczpcL1wvb
    XktYXV0aC1zZXJ2ZXIuY29tIiwianRpIjoiMWI2YjMxMTItMzkyZi00MzIxLTk2YjktNzk
    yYjhhMjcxOTliIiwiaWF0IjoxMzczNjQyMTc2fSwiY2xpZW50Ijoic3lzdGVtIEEiLCJzY
    29wZSI6WyJyZWFkIiwgInNlYXJjaCJd

 

Finally, the above string representation of a JWT security token is what gets transmitted over the wire as a message header or url query parameter.

 

 

Sources: