How to secure Spring Boot with JWT Authentication and Authorization
Tags: development, webdev, programming, java
Published: 2023-05-11 06:07:45

Hello learners, here we are going to learn about spring security implementation with spring boot3.0 and JWT.

JWT (JSON Web Tokens) is a standard for representing claims securely between two parties. It is a compact, URL-safe means of representing claims to be transferred between two parties. A JWT consists of three parts: a header, a payload, and a signature.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kd35nvvv41e1xn1f8566.png)


Header consist of algorithm and token type, Payload consist of subject,name,issuedat, Verify Signature is the combination of encoded header,payload and secret key. JWT token is a combination of these three.

Spring Security can be integrated with JWT to secure web applications by generating, parsing, and validating JWTs.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/npdy4avhsk59alvbnt6a.png)


The following is a overview of how JWT authentication and authorization works in Spring Boot:

**User authentication**: When a user logs in to the system, the server verifies the user's credentials, such as their username and password. If the credentials are correct, the server generates a JWT for the user and returns it to the client.

**JWT creation**: The server creates a JWT by encoding the user's identity information and other necessary data, such as expiration time, into a JSON object. The JSON object is then signed using a secret key or public/private key pair.

**Token storage**: The client stores the JWT locally, usually in a cookie or local storage.

**Authorization**: For each subsequent request, the client sends the JWT in the request header. The server verifies the JWT's signature and decodes its contents to extract the user's identity information and other details. Based on this information, the server can then authorize the user to access certain resources or perform certain actions.

**Token validation**: The server can also validate the JWT to ensure that it has not been tampered with and has not expired. If the token is invalid, the server can reject the request or request the user to log in again.

## Steps to Implement JWT

Step 1: Add the JWT dependencies

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/stjmnmsg4waa12jujj9l.png)


Step 2: Create a endpoint to authenticate and generate JWT

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r53izbkopq2x9tczt02l.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ezcst3414xp6lgwlq0qz.png)


In CreateToken method, we are creating token by setting claims,subject,issued and expiration date, signature.

Step 3: Create a filter to validate JWT

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mcx7ls3tqnnfjo5ztuc5.png)


create a class for filter and extends with OncePerRequestFilter, override doFilterInternal method and invoke authorization token from header. Validate the token by extracting username and expiration date from the token. This filer is used to validate the JWT token for each API call.

Step 4: Add the configuration to authorize API calls

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l4gu3fk0rwqaz61fw9qx.png)


Create a class and add a method to authorize, in above code given access to "/products/new","/products/authenticate" endpoints to all users, for "/products/**" endpoint only authenticated users with valid JWT can access.

**Testing the implementation**

Authenticating and Generating the token

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zfchpdxavnvmjbkcamq3.png)


Copy the generated token and add it to other API call, I'm accessing the below API with Admin credentials

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/48sc0o626r2dryzo3dkr.png)


If we try to access the API with Admin credentials where only user can access will get 403 Forbidden error