Securing Spring Boot Microservices with Spring Security

Overview

Basically, our microservices are secured this way :

  1. The user provides his credentials via a public endpoint
  2. If authenticated, the server returns an authentication token (JWT)
  3. The JWT is attached to each subsequent request via an HTTP header: Authorization:Bearer TOKEN

User Microservice

This microservice uses a MySQL database. We begin by creating the Account table:

Below is a script to insert some dummy data:


The Account entity will be created using JPA:



The account repository:



User Principal

We create a class named UserPrincipal which implements UserDetails. In order to be accessible by all microservices, this class is located in our shared module.


JWT Token Service


This service is responsible for creating expiring JWT. We can also parse a JWT for getting the UserPrincipal. We use the io.jsonwebtoken dependency for that.


Account Service


The account service via the login method logs in a user and returns a JWT. This service is located in the user module.


Authentication Filter


The authentication filter is responsible of extracting the JWT from the Authorization header.


Authentication Provider

The authentication provider is responsible of validating the JWT. If the token is valid, we return a UserPrincipal otherwise we throw an exception. As you can see we don't access the database at all (our stateless solution!). In order to be accessible by all microservices, this class is also located in our shared module.


Security Config

We will configure in the next configuration class all the Spring security staff. In order to be available to all modules, this configuration will be placed in our shared module.


As you can see, all non public endpoints are protected.

Public Controllers

In the user module, we create a controller for logging in a user into the application.


Protected Controllers

The authenticated user can be accessed via the AuthenticationPrincipal annotation.


Testing

You can test a protected controller this way :



Thanks for sharing...



Comments

Popular posts from this blog

Spring JPA : Using Specification with Projection

Chip input using Reactive Form