JWT Authentication for Security

Posted By :Hemant Chauhan |28th February 2020

In this article, we will take a look at what JSON Web Token(JWT) Authentication security and all about

We will start with basic defination of JWT & how it works, and finally create a simple Spring boot application that will take some data from database and insert it into a JWT.


What is JWT & its need?


A JSON Web Token (JWT) is a compact and secure , and self-contained way of securily transmitting information between multiple orgainization in the form of a JSON object.

Say when you login to an app, like say Instagram. Instagram allows users to log in using their Facebook profile. So when the user wants to log in Facebook, the Instagram contacts Facebook’s Authentication server with his credentials like username and password.

Once the Authentication server verifies the user credentials, it will create a json web token and send to the user. The app now get token and allow the user to access its data.

JWT Structure

Json web token Structure is divided into three parts-

1. Header

2. Payload

3. Signature

1. Header consist of two parts:

1. Token type 2.Hashing algorithm


           "alg": "HS256",
           "typ": "JWT"

2. Payload is where the actual information is stored.


          "sub": "65165751325",
          "name": "Rahul",
          "admin": true

3. Signature: To create a Singnature part we have to take encoded header, encoded payload,a secret key, and the algorithm of header






To easily verify,decode, generate, or others advance features of JWTs, go to JWT.IO Debugger by Auth0.


JWT Working flow



















Now that we understand only what is JSON and how its look like , lets take a example how to build a simple Spring boot application using JWT authentication for securing our exposed Restful Api.


Creating the Project

To generate the project we uses Spring Initializr web tool.

1. Go to http://start.spring.io

2. Enter Artifact as “demo”

3. Change Package Name to “com.example.jwtsecurity

4. Select JPA, WEB, MYSQL, Spring-Security, java-JWT dependencies.

5. Click Generate Project to download the project.


Define the Application properties as follows-

spring.datasource.url = jdbc:mysql://localhost:3306/databasename
spring.datasource.username = root
spring.datasource.password = root
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect


Create the entity class as follows-:

package com.demo.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
@Table(name = "user")
public class DAOUser {
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private long id;
        private String username;
        private String password;
// default Constructor
// Constructor using fields
// getter and setters

Define the UserDTO model class as follows. This class is responsible for getting data from user and passing it to the DAO layer.

package com.demo.model;
public class UserDTO {
        private String username;
        private String password;
//getter and setters

we define the UserDao which is an interface extends Crud Repository

public interface UserDao extends CrudRepository<DAOUser, Integer> {

Expose a POST API /authenticate using the JwtAuthenticationController. This POST API gets the username and password of the user in the Postman body. By the help of Spring Authentication Manager, we authenticate the username and password. If the username and password are valid and match to the database data , then a JWT token is created and provided to the client.

public String generateToken(@RequestBody LoginDto logindto) throws Exception {
    try {
                new UsernamePasswordAuthenticationToken(logindto.getUsername(), logindto.getPassword())
    } catch (Exception ex) {
        throw new Exception("inavalid username/password");
    return jwtTokenUtil.generateToken(logindto.getUsername());


JWT Filter

This class extends the Spring Web Filter OncePerRequestFilter class. For any incoming request, this class gets first executed. It checks if the request has a valid JWT token, then it sets the authentication in context to specify that the current user is authenticated.

JWT AuthenticationEntryPoint

It extends Spring's AuthenticationEntryPoint class and override its commence method. It sends error code 401 for every unauthenticated request.


WebSecurityConfig is a convenience class that allows customization to both HttpSecurity and WebSecurity. This securityconfig class extends the WebSecurityConfigurerAdapter.

JWT Util

The JwtTokenUtil is used for performing JWT operations like creation and validation. Validations include the time in which token is expires. For achieving this., it makes use of the io.jsonwebtoken.Jwts.

public String generateToken(String username) {
        Map<String, Object> claims = new HashMap<>();
        return createToken(claims, username);
    private String createToken(Map<String, Object> claims, String subject) {
        return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
          .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 2))
                .signWith(SignatureAlgorithm.HS256, secret).compact();
    public Boolean validateToken(String token, UserDetails userDetails) {
        final String username = extractUsername(token);
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));


Then run the spring boot Application

Open the POSTMAN app and send a post request with the JSON object ie username and password in its body. If the username and password information are present in the database than it return the token if not present then it gives error.

As shown below the result will be a JSON Web Token:






















If you copy the given token into the JWT.IO Debugger, you will see that the username and password is same, but with a few extra things(header,payload & signature).


















Validate the JSON Web Token

Using the above-generated token in the header and try accessing the URL localhost:8080/hello as follows:
















Contrasted with other web tokens like Simple Web Tokens (SWTs) or Security Assertion Markup Language (SAML), JWT is a lot less complex as it depends on JSON which is more obvious than XML.
On the off chance that we encode the JSON, it will turn out to be much more littler in size than SAML, making it simpler to go in HTML and HTTP situations.

Talking from a use perspective, JWTs are utilized at Internet scale. This implies it is simpler to process on the client's gadgets, be it PCs or portable.

Aside from authenctication, JSON Web Token are an extraordinary and make sure about method for transmitting information between different gatherings. The way that JWTs have marks makes it simpler for everybody to effectively recognize the sender of data. All you need is the right key.

I trust this post helped you see how to execute a straightforward JSON Web Token Authentication in your application. Don't hesitate to remark and ask/recommend anything! I'd be glad to talk ?

About Author

Hemant Chauhan

Hemant is an accomplished backend developer with extensive experience in software development. He possesses an in-depth understanding of various technologies and has a strong command over Java, Spring Boot, MySQL, Elasticsearch, Selenium with Java, GitHub/GitLab, HTML/CSS, and MongoDB. Hemant has worked on several related projects, including Tessaract OCR, Sikuli with Selenium Automation, Transleqo, and currently, SecureNow. He excels at managing trading bots, developing centralized exchanges, and has a creative mindset with exceptional analytical skills.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us