Implement JWT Token in 10 Minutes: Quick Guide

A source guide for implementing JWT web token with your Java project quickly.2 min


1
1 share, 1 point
jwt-token-json-web-token-implementation-in-java-angular-project

In this article, we will focus on what is JSON Web Tokens (JWT), What are the benefits of using them, and how you can implement JWT token easily with any java framework (like Spring, Spring boot, etc.)

Java support for JWT (JSON Web Tokens) — Mostly JWT can be used in Hybrid Applications like Angular as a Frontend and Java as a Backend.

Most developers are using the JWT Token for Java and Android projects because of its own benefits! In addition to that, nowadays people are using Hybrid applications, let’s say for example Angular/ReactJS/VueJS as frontend, Java/.Net/Php as backend, hence there might be a possibility for multiple backends (i.e. split up into separate micro-service authentication servers, databases, image processing servers, etc.) In such scenarios, the session cookie we get from one server won’t correspond to another server.

Cover Image Credits: JWT token (JSON web token) implementation in Java Angular project in 10 Minutes | Image By Author

Benefits of using JWT Tokens

  1. It’s Portable: A single token can be used with a number of backends. You can use it for restful APIs, web MVC and create generic third-party libraries — so others can also consume your web services.
  2. JWT (JSON Web Tokens) Are Better Than Session Cookies
  3. Faster in performance: It reduces the network round trip time.
  4. It is stateless, No need to worry about the session management: The JWT is a self-contained token that has authentication information, expiration time information, and other user-defined claims digitally signed.
  5. Loosely Coupled: It is decentralized, the token can be generated anywhere. Authentication can happen on the resource server or easily separated into its own server.
  6. It is more suitable for micro-service architectures: Instead of making a session and setting a cookie, the server will send you a JSON Web Token instead.

What Are JWTs?

JWTs are an encoded representation of a JSON object. The JSON object consists of zero or more key/value pairs, where the keys are strings and the values are arbitrary JSON values. JWT is useful to send such information in the clear (for example, in an URL) while it can still be trusted to be unreadable (i.e. encrypted), unmodifiable (i.e. signed), and url-safe (i.e. Base64 encoded).

JWTs can have different usages: authentication mechanism, url-safe encoding, securely sharing private data, interoperability, data expiration, etc. Regardless of how you will use your JWT, the mechanisms to construct and verify it are the same. So, let’s see how we can very easily achieve that with the JSON Web Token for the Java projects.

Generate JWT Tokens

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import io.jsonwebtoken.*;
import java.util.Date;    
 
//Sample method to construct a JWT
private String generateJWT(String id, String issuer, String subject, long ttlMillis) {
 
    //The JWT signature algorithm we will be using to sign the token
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
 
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);
 
    //We will sign our JWT with our ApiKey secret
    byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey.getSecret());
    Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
 
    //Let's set the JWT Claims
    JwtBuilder builder = Jwts.builder().setId(id)
                                .setIssuedAt(now)
                                .setSubject(subject)
                                .setIssuer(issuer)
                                .signWith(signatureAlgorithm, signingKey);
 
    //if it has been specified, let's add the expiration
    if (ttlMillis >= 0) {
    long expMillis = nowMillis + ttlMillis;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp);
    }
 
    //Builds the JWT and serializes it to a compact, URL-safe string
    return builder.compact();
}

Parse and Verify JWT Tokens

import javax.xml.bind.DatatypeConverter;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.Claims;
 
//Sample method to validate and read the JWT
private void verifyJWT(String jwt) {
 
    //This line will throw an exception if it is not a signed JWS (as expected)
    Claims claims = Jwts.parser()         
       .setSigningKey(DatatypeConverter.parseBase64Binary(apiKey.getSecret()))
       .parseClaimsJws(jwt).getBody();
    System.out.println("ID: " + claims.getId());
    System.out.println("Subject: " + claims.getSubject());
    System.out.println("Issuer: " + claims.getIssuer());
    System.out.println("Expiration: " + claims.getExpiration());
}

Why We Need Token-Based Authentication System?

The token-based authentication systems allow users to enter their username and password in order to obtain a token which allows them to fetch a specific resource without entering their username and password at each request. Once their token has been obtained, the user can use the token to access specific resources for a set time period.

JWT (pronounced ‘jot’) is a token-based authentication system. It is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is digitally signed using JSON Web Signature. The JWT is a self-contained token that has authentication information, expiration time information, and other user-defined claims digitally signed.

Wrapping up...

I obtain an immense amount of satisfaction from helping others attain their goals and reach their potential through technology. Even if you wish to reach out and say "Hello", I sincerely appreciate all of the wonderful correspondence I receive each day from readers. You all enrich my life, and I hope I am able to do the same for you all as well.

If you find joy and value in what I do, please consider supporting my work with a donation — however much you can afford, it means and helps more than you can imagine.

You can give tips too using Buy me a coffee.

adsense


Discover more from 9Mood

Subscribe to get the latest posts sent to your email.


Like it? Share with your friends!

1
1 share, 1 point

What's Your Reaction?

Lol Lol
2
Lol
WTF WTF
0
WTF
Cute Cute
0
Cute
Love Love
2
Love
Vomit Vomit
0
Vomit
Cry Cry
0
Cry
Wow Wow
2
Wow
Fail Fail
0
Fail
Angry Angry
1
Angry
Unbounded Soul

22, searching for meaning in life.

Hire me for professional programming & Tech support-related work at a reasonable cost!

0 Comments

Leave a Reply

Choose A Format
Story
Formatted Text with Embeds and Visuals
List
The Classic Internet Listicles
Ranked List
Upvote or downvote to decide the best list item
Open List
Submit your own item and vote up for the best submission
Countdown
The Classic Internet Countdowns
Meme
Upload your own images to make custom memes
Poll
Voting to make decisions or determine opinions
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Personality quiz
Series of questions that intends to reveal something about the personality
is avocado good for breakfast? Sustainability Tips for Living Green Daily Photos Taken At Right Moment