JWT Authentication in Spring

What is JWT?

JWT is the JSON-based open-source standard for creating access tokens that allow us to secure communication between client and server. It is compact, readable, and digitally signed.

The purpose of using JWT is to ensure the authenticity of the data. JWT is signed and encoded, not encrypted.

How does it work?

  1. First, we need to authenticate the user using client authentication.We can use local authentication or service-based like Google
  2. The authentication server will confirm that the user is authorized or not
  3. Now here, a JWT token is generated. This token is sent to the client-side application
  4. For each request, the server decrypts the token and confirms if the client has permission to access the resource by making a request to the authorization server.

What is token composed of?

They are composed of three parts:

  • Header: It contains metadata.Information about type of token and the algorithm.
  • Payload: It contains a series of attributes that are encrypted into the token
  • Signature: It contains concatenated and encrypted header and payload(Header+”.”+Payload+secret key).This part is used to verify the integrity of the message.

Creating a Spring boot application

First, we need to generate a maven project. For this, we go to the spring initializer website and generate a maven project with java and spring. We need to fill in the group name, project name. The generated file is a .jar file.

Spring initializer

We can also add dependencies that we want by clicking on the Add dependencies tab in the top right corner. We need to add three dependencies namely Spring security, Lombok, Spring Web.

Once we generate and download it, we unzip and build it with the maven package command on the root of our project.

Implementing API

We used the following annotations which work

  • The RestController is to enable this class as a REST controller and allow it to intercept requests to the server
  • The RequestMapping allows making a call to the server when routed to a specific route

For starting the application we execute the “mvn spring-boot: run”. At this point, we haven’t added any security settings. If we invoke the endpoint of our service (http://localhost:8080/hello), it will return the default message

Authentication

Now we will create another REST controller to implement the authentication process through a username/password login:

Here we are creating the token using the getJWTToken() class. It includes the information that contains when this token will get expire. This is used to authorize the request access whenever needed

Now we are doing some configuration in classes

Here we are defining the authentication to the calls that have been made . Thus it allows us to have specific access. Here we are using UsernamePasswordAuthentication Filter and make sure that the user is claimed

WebSecurityConfigurationAdapter is used to apply that filter.

Authorization

Here we implement the authorization process, which is capable of intercepting invocations to protected resources to recover the token and determine if the client has permissions or not.

To do this, we will implement the JWTAuthorizationFilter:

This filter intercepts all calls to the server (extended from OncePerRequestFilter) and:

  • Checks the existence of the token (checkJWTToken(…))
  • If it exists, it decrypts and validates (validateToken(…))
  • If everything is ok, it adds the necessary configuration to the Spring context to authorize the request (setUpStringAuthentication(…))

For this last point, the GrantedAuthority object that was included in the token is used during the authentication process.

Testing our API

To do so, we can use Postman, a simple Chrome extension that allows us to execute and monitor requests.

  • We start our server by executing the command “mvn spring-boot: run
  • From Postman, we make a GET request to /hello and verify that it gives us a 403 since the resource is protected.
  • From Postman, we make a POST request to /user to authenticate, including username and password, and we obtain an access token:

Conclusions

We have demonstrated a simple way to authenticate and authorize requests to a REST API built with Java and Spring Boot

References:

  1. https://auth0.com/docs/tokens/json-web-tokens/json-web-token-claims
  2. https://www.freecodecamp.org/news/how-to-setup-jwt-authorization-and-authentication-in-spring/

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store