Open Source JWTs For Any Java App

JJWT is the easiest library for creating and verifying JSON Web Tokens (JWTs) on the JVM.
Just drop JJWT into any Java application. Check it out in action!

View on GitHub

First, what is a JSON Web Token, or JWT (pronounced “jot”)? In a nutshell, a JWT is a secure and trustworthy standard for token authentication. JWTs allow you to digitally sign information (referred to as claims) with a signature and can be verified at a later time with a secret signing key. The spec is also designed with advanced features that help against CSRF, man-in-the-middle, and replay attacks.

What is Token Authentication?

The process by which an application confirms user identity is called authentication. Traditionally, applications persist user identity through session cookies which rely on session IDs stored server-side. In this structure, developers are forced to create session storage that is either unique and server-specific, or implemented as a completely separate session storage layer.

Token authentication is a more modern approach, designed solve problems server-side session IDs can’t. JWTs provide a structured way to declare who a user is and what they can access. The use of tokens in place of session IDs can lower your application’s server load, streamline permission management, and provide better tools for supporting a distributed or cloud-based infrastructure.

JWTs handle some of the problems with passing information from a client to a server. A JWT allows the server to verify the information contained in the token requiring the state to be stored on the server. Token authentication generates tokens for your users after they present verifiable credentials. The initial authentication could be by username/password credentials, API keys or even tokens from another service.

Anatomy of a JWT

If you encounter a token in the wild, it will look like this:


        dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk..."
        
    
This is a Base64 encoded string. If you break it apart you’ll actually find three separate sections:
        
        eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9
        .
        eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt
        cGxlLmNvbS9pc19yb290Ijp0cnVlfQ
        .
        dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
        
        

Line 1 is a header which describes the token. Lines 3 and 4 are the claims (sometimes called the payload) which contains the juicy bits, and Line 6 is the signature hash that can be used to verify the integrity of the token (if you have the secret key that was used to sign it).

When we decode the the claims we get this nice, tidy JSON object:

        
        {
        "sub": "users/TzMUocMF4p",
        "name": "Robert Token Man",
        "scope": "self groups/admins",
        "exp": "1300819380"
        }
        
        
The claims tell the application, at minimum:

Because the token is signed with a secret key, the application can verify its signature and implicitly trust what is being claimed.

What the Heck is OAuth?

OAuth 2.0 is a set of protocols that can delegate authentication or provide authorization when interacting with another service. It is widely adopted across many mobile and web applications. Stormpath uses OAuth because it is an industry standard that can be leveraged by any compliant library, and we currently support three of OAuth’s most used grant types:

Access and Refresh Tokens

Also within the OAuth paradigm, there are two token types: Access and Refresh Tokens. When you first authenticate, your application (and thus your user), is given both tokens, but the Access Token is set to expire after a short period (this duration is under your control). Once the initial Access Token has expired, the Refresh Token will allow your application to obtain a new Access Token. Refresh Tokens have a set expiration, allowing for unlimited use up until that expiration point is reached. Both Access and Refresh Tokens have built-in security to prevent tampering and are only valid for a specific duration.

Create and Validate JSON Web Tokens

So, you’re sold on tokens, now, how do you use them in your application?

JJWT is a Java library providing end-to-end JSON Web Token creation and verification, developed by our CTO, Les Hazlewood. Forever free and open-source (Apache License, Version 2.0), it was designed with a builder-focused interface hiding most of its complexity.

Creating

Because of JJWT’s fluent interface, the creation of the JWT is basically a two-step process:

  1. The definition of the internal claims of the token, like Issuer, Subject, Expiration, ID and signing Key
  2. The compaction of the JWT to a URL-safe string, according to the JWT Compact Serialization rules

The final JWT will be a Base64 encoded string signed with the specified signature algorithm using the provided key. After this point, the token is ready to be shared with the other party.

Validate The JWT

Once you have a JWT, you typically deliver it back to the client that requested it. The client then stores it and passes the Access Token property in requests to your application. This is usually done with either a cookie value, or an authorization header in HTTP. For example:

    
        HTTP/1.1
        GET /secure-resource
        Host: https://yourapplication.com
        Authorization: Bearer eyJraWQiOiIzMUUzRDZaM0xaMVdFSEJGWVRQRksxRzY4IiwiYWxnIjoiSFMyNTYifQ.eyJqdGkiOiI2a3NjVFMyUjZuYlU3c1RhZ0h0aWFXIiwiaWF0IjoxNDQ1ODU0Njk0LCJpc3MiOiJodHRwczovL2FwaS5zdG9ybXBhdGguY29tL3YxL2FwcGxpY2F0aW9ucy8zUUlNbEpLS04yd2hHQ1l6WFh3MXQ4Iiwic3ViIjoiaHR0cHM6Ly9hcGkuc3Rvcm1wYXRoLmNvbS92MS9hY2NvdW50cy8xeG15U0dLMXB5VVc1c25qOENvcmU1IiwiZXhwIjoxNDQ1ODU4Mjk0LCJydGkiOiI2a3NjVE9pTUNESVZWM05qVTIyUnlTIn0.VJyMOicMOdcOCtytsx4hoPHy3Hl3AfGNfi2ydy8AmG4
        
    

Validating the JWT allows you to verify its authenticity (by checking its digital signature you can check that it is not expired and verify that it hasn’t been tampered with) and get information about the user sending the token.

Exceptions

JJWT carries out a variety of validations while working with the JWT. All JJWT-related exceptions are RuntimeExceptions, with JwtException as the base class.

These errors cause specific exceptions to be thrown:

Are Tokens Secure?

The real question here is, are you using them securely? At Stormpath, we follow these best practices, and encourage our clients to do the same:

JJWT is Open Source

JJWT is super easy to use and understand. If you need to create and verify JSON Web Tokens, it’s 100% the tool for you. And, like many libraries Stormpath supports, JJWT is completely free and open source (Apache License, Version 2.0), so everyone can see what it does and how it does it. Do not hesitate to report any issues, suggest improvements, and even submit some code!