JSON Web Token (JWT) for Beginners
- Details
- Written by Nam Ha Minh
- Last Updated on 07 October 2024   |   Print Email
If you’re new to JSON Web Token (JWT), reading this article till the end will help grasp the most basic and fundamental concepts. Properly understanding JWT is crucial for securing REST APIs based on OAuth2 workflow, which involves creating, parsing and validating access tokens which comply with the JWT format.
In the following text, you’ll understand what JWT is, where it is used, the structure of a JWT, and some popular Java libraries that support working with JWT.
1. What is JWT?
JSON Web Token (JWT) is an Internet standard that defines a compact and self-contained way to securely transmit information between parties as a JSON object. It is standardized in the RFC 7519.
JWT is widely used as the format for access tokens in REST API security, specifically for authorization between a client and a server. Access tokens are preferred over traditional credentials (such as usernames and passwords) because they are self-contained, carrying all the necessary authorization information, and are secured through signing and encryption. This makes them well-suited for the stateless nature of REST APIs. Additionally, access tokens have short expiry times, which means they quickly become unusable if stolen, thus improving the security of REST APIs.
Technically, a JWT is a string that represents a set of claims as a JSON object.
- claim is a piece of information asserted about a subject
- a claim is represented as a name/value pair, consisting of a claim name and claim value
- a claim name is always a string, while a claim value can be any valid JSON value
Here is a typical example that explains the use of a claim:
- A server could generate an access token with the claim “logged in as administrator” and issue it to the client.
- The client could then use that token to prove it is logged in as an administrator in subsequent requests.
JWTs are designed to be compact, making them easy to use in space-constrained environments such as HTTP Authorization header and URI query parameters.
Tokens can be digitally signed using either a secret key or a public/private key pair, allowing them to be verified and trusted. RFC 7515 defines standard for JSON Web Signature (JWS).
Tokens can be also encrypted for stronger security. RFC 7516 specifies the standard for JSON Web Encryption (JWE).
2. Where is JWT used?
JWTs are widely used in REST API authorization following OAuth2, the Open Authorization specification. The following diagram illustrates where JWTs are used in the OAuth2 abstract protocol workflow:
As you can see, the authorization server issues a JSON Web Token when the client requests a new access token with a valid authorization grant. The access token can be signed and encrypted for enhanced security.
When the client needs to access a protected resource, it sends a request carrying the issued JWT to the resource server. If the access token is valid, the protected resource is sent to the client.
That being said, JWT is used as a means of authorization between the client and the server in REST API calls. The client doesn’t have to expose credentials (username and password) repeatedly. The client’s credentials are only required to obtain the access token, and subsequent requests are authorized via the JWT contained in access token.
The following example illustrates a response body from the authorization server that contains the access token as a field value in a JSON document:
{ "access_token": "<JWT: eyJhbGciOiJIUzUxMiJ9…>", "token_type": "Bearer", "expires_in": 299 }
Then access token is then used in the HTTP Authorization request header as follows:
curl -H "Authorization: Bearer <JWT: eyJhbGciOiJIUzUxMiJ9… >" localhost:8080/v1/locations
This is a curl command used to get a protected resource from the server. The client is authorized via the JWT sent in the Authorization request header.
Refer to this guide if you want to learn more about REST API testing using curl.
3. The Structure of a JWT
Next, let’s understand the structure of a JSON Web Token by looking at the following picture:
You see, a JWT consists of three parts separated by dots: the header, the payload and the signature. The header is a JSON object that specifies the type of the token and the signing algorithm. For example:
{ "typ":"JWT", "alg":"HS256” }
This means that the token is of type JWT and is signed with the HMAC SHA-256 symmetric keyed hashing algorithm.
The payload is a JSON object that represents a set of claims. For example:
{ "sub": "1234567890", "name": "Nam Ha Minh" "iss": ”Codejava.net", }
This payload conveys data about the subject, name and issuer. The Internet Assigned Numbers Authority (IANA) defines some registered claim names, such as sub (subject), name, iss (issuer), aud (audience), exp (expiration time), etc.
The header and the payload are encoded using Base64 URL encoding format, and the signature is the result of signing the header and the payload using either a secret key or a pair of public and private keys. The signature is also base64url-encoded.
Below is example of a full JWT string:
eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI1LFRvbSdzIEFwcCIsImlzcyI6IkNvZGVKYXZhIiwicm9sZXMiOiJSRUFERVIiLCJpYXQiOjE3MDg0MTk1OTQsImV4cCI6MTcwODQxOTc3NH0.MkYo8UuEtTGRk_bL9m0tkfbMAlMVqlvN1XjUxnEhNIwlmBSDP92Dv_HcN7RkW0NqgUmXxg5gGF1EAK4YRNLNrw
If you’re curious, try decoding this JWT as instructed in this guide.
4. Java Libraries for JWT
If you’re implementing security for your REST APIs with Java, you may need to use some well-crafted libraries recommended below:
- The java-jwt library by Auth0 provides a simple API for creating, signing, parsing, and validating JSON Web Tokens (JWTs) in Java applications. It supports various cryptographic algorithms like HMAC and RSA for secure token signature verification and allows adding custom claims to JWTs for flexible authentication and authorization purposes. The library is widely used in token-based security implementations such as API protection, stateless authentication, and role-based access control.
- The jjwt (Java JWT) library by jwtk is a robust and flexible library for creating, parsing, and verifying JSON Web Tokens (JWTs) in Java. It supports a wide range of algorithms (e.g., HMAC, RSA, ECDSA) and simplifies token management by offering easy-to-use APIs for adding claims, managing token expiration, and ensuring secure token validation.
- The Nimbus JOSE+JWT library provides comprehensive support for handling JSON Web Tokens (JWT) and JSON Object Signing and Encryption (JOSE) in Java. It offers a wide range of cryptographic algorithms for signing, encryption, and decryption, and is highly configurable, making it suitable for secure token management in complex applications.
- Spring OAuth2 provides robust support for securing applications using OAuth 2.0 and JSON Web Tokens (JWT), offering tools for token creation, parsing, and validation. It seamlessly integrates JWT-based authentication and authorization, enabling secure stateless communication between clients and resource servers by verifying token signatures and claims.
References:
Other REST API Tutorials:
- Java RESTful Web Services Tutorial for Beginner with Jersey and Tomcat
- Java CRUD RESTful Web Services Examples with Jersey and Tomcat
- Spring Boot Hello World RESTful Web Services Tutorial
- Spring Boot RESTful CRUD API Examples with MySQL database
- Spring Boot File Download and Upload REST API Examples
- Spring Boot REST API CRUD with HATEOAS Tutorial
- How to Use curl for Testing REST APIs (Test CRUD Operations)
- How to Use Postman for Testing REST APIs (Test CRUD Operations)