Adding security to micro-services — Spring boot (Gateway filter) + JWT authentication (Part 2)

Mayank Yaduvanshi
4 min readMay 22, 2023


This is the second part of my previous article about creating micro-services with spring boot framework-

Now we will add some security to prevent unauthorised access to out services(apis). As we are talking about micro-services which means that we should and have a stand-alone authentication service to provide authentication mechanism to each service in a single place, instead of implementing it in each service. And also we should have a common place to authorising incoming requests.

From the above scenario we can conclude that we need following to implement -

  1. An Authentication service — for identifying users
  2. An Authorisation filter — for filtering un-authorised requests

We will create each of them one-by-one, Let’s Start!

NOTE: I am using IntelliJ IDEA as IDE for this project, all the instructions and coding sample are from it.

Before start, If you still haven’t read my previous article (link at the top), you can clone this Github repo mayank042/spring_microservice_sample: Sample application demonstrating the spring boot micro-service architecture ( and checkout the tag — v1_no_auth

Generating the JWT token

Authentication Service

We use this service to generate a JWT token, that can be later passed in authentication header of api requests. Will verify the token in Gateway service.

Assuming we have a User table in out database with email, password and a role. So we will create an User entity with UserRepository to fetch user details.

Start by creating a new spring module inside root module -

File → New → Module → Spring initializr

(using spring boot version — 2.7.x)

Intellij IDEA — new spring module

pom.xml — add JPA dependency



</dependency> — entity class

@Table(name = "user")
public class User {

@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "Id", nullable = false)
private Long id;

@Size(max = 255)
@Column(name = "Email")
private String email;

@Size(max = 255)
@Column(name = "Password")
private String password;

@Size(max = 255)
@Column(name = "Role")
private String role;
} — JPA repository for User entity

public interface UserRepository extends JpaRepository<User, Long> {

User findByEmail(String email);

} and

public interface UserService {

User getUserByEmail(String email);

public class UserServiceImpl implements UserService {

private final UserRepository repository;

public User getUserByEmail(String email) {

return Optional.ofNullable(repository.findByEmail(email))
.orElseThrow(() -> new RuntimeException("User with email is not found."));


Till here we have created an POST api /authenticate to handle authentication requests, and service and repository to find the User by email.

Now we will use a JWT library to generate the token.

Also note that we do not store passwords in database directly, instead we use some encryption and decryption techniques, to store and retrieve the password.

Now, create an controller to handle the authentication requests and return with JWT token.

public class UserController {

private final UserService userService;

@PostMapping(value = "/authenticate")
public ResponseEntity<String> authenticateUser(
@Valid @RequestBody AuthenticationRequest request
) {

User user = userService.getUserByEmail(request.getEmail());

var password = CryptoUtils.decrypt(user.getPassword());

if (user.getPassword().equals(password)) {
// generate token
var token = jwtTokenUtil.generate(user, "ACCESS");

return ResponseEntity.ok(new AuthToken(token));

return ResponseEntity.badRequest().build();

Verifying JWT token (Applying gateway request filter)

Gateway service

Its time to put out JWT token on work, we will use that to verify and block invalid/unknown/non-authorised requests to our all services, by applying an request filter in out prev. gateway service.

pom.xml — Add some JWT dependencies first -

</dependency> — a gateway filter

public class AuthenticationFilter implements GatewayFilter {

private RouterValidator routerValidator;
private JwtUtil jwtUtil;

public String TOKEN_PREFIX;

public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();

if (routerValidator.isSecured.test(request)) {
if (this.isAuthMissing(request) || this.isPrefixMissing(request))
return this.onError(exchange, "Authorization header is missing in request", HttpStatus.UNAUTHORIZED);

final String token = this.getAuthHeader(request);

if (jwtUtil.isInvalid(token))
return this.onError(exchange, "Authorization header is invalid", HttpStatus.UNAUTHORIZED);

this.populateRequestWithHeaders(exchange, token);
return chain.filter(exchange);


private Mono<Void> onError(ServerWebExchange exchange, String err, HttpStatus httpStatus) {
ServerHttpResponse response = exchange.getResponse();
return response.setComplete();

private String getAuthHeader(ServerHttpRequest request) {
var header = request.getHeaders().getOrEmpty("Authorization").get(0);
return header.replace(TOKEN_PREFIX,"").trim();

private boolean isAuthMissing(ServerHttpRequest request) {
return !request.getHeaders().containsKey("Authorization");

private boolean isPrefixMissing(ServerHttpRequest request) {
var header = request.getHeaders().getFirst ("Authorization");
assert header != null;
return !header.startsWith(TOKEN_PREFIX);

private void populateRequestWithHeaders(ServerWebExchange exchange, String token) {
Claims claims = jwtUtil.getAllClaimsFromToken(token);
.header("id", String.valueOf(claims.get("id")))
.header("roles", String.valueOf(claims.get("roles")))
.header("tenantId", String.valueOf(claims.get("tenantId")))

Here AuthenticationFilter implements the GateFilter which provides us with a filter method to chain and filter requests after validation.

inside filter method, we are checking that Authentication header should present in the request and the JWT token should not expired and valid. If checks failed we can return response of 401 unauthorised

Applying the filter -

public class GatewayConfig {

AuthenticationFilter filter;

public RouteLocator routes(RouteLocatorBuilder builder) {
return builder.routes()
.route("user-service", r -> r.path("/api/users/**")
.filters(f -> f.filter(filter))
.route("auth-service", r -> r.path("/api/auth/**")


Note how we applied the filter on the user-service, we can do the same with all the service we have and same authentication will work for all.

Congratulation! we have successfully added some basic security to our services.



Mayank Yaduvanshi

Full Stack Software Developer, Experienced in Angular, Flutter, Spring boot, NodeJs, MySQL, MongoDB, AWS, Google Cloud, Docker, Git, JIRA.