Introduction
Welcome to the next step in building our microservices platform! In the previous lesson, we configured our API Gateway to act as a clean, stable entry point to our backend, abstracting away the internal details of our auth-service and blog-service.
So far, a request to create a blog post flows like this: Client -> API Gateway -> Blog Service. The gateway simply forwards the request. However, this is insecure. Anyone can call the "create post" endpoint. In a real system, the blog-service must verify the user's identity before creating a post.
This lesson tackles a core concept in microservices: inter-service communication. You will learn how the blog-service can communicate with the auth-service to validate the JWT sent by the user, thereby securing our posts endpoint.
1. Choosing the Right Tool for the Job
When one Spring Boot service needs to call another, there are several tools at our disposal.

RestTemplate: The classic, synchronous client. It's straightforward but requires you to manually build URLs, set headers, and handle responses. This can lead to a lot of boilerplate code.WebClient: The modern, reactive client from Spring WebFlux. It's non-blocking and excellent for high-concurrency scenarios, but it introduces the complexity of reactive programming (Mono/Flux).OpenFeign: A declarative REST client from the Spring Cloud family. You simply define a Java interface and annotate it. Spring generates the implementation for you at runtime. It's incredibly clean and concise, making it a favorite for microservice-to-microservice communication.
MERN Stack Comparison
In the MERN world, you would typically use a library like axios to make an HTTP request from one service to another.
// In Node.js (e.g., blog-service)
async function validateUserToken(token) {
try {
// Manually making a request to the auth service
await axios.get('http://auth-service:8081/api/v1/auth/validate', {
params: { token }
});
return true;
} catch (error) {
return false;
}
}
OpenFeign achieves the same goal but in a more integrated, type-safe, and declarative way, hiding the underlying HTTP client implementation from you. For our production-style system, OpenFeign is the ideal choice.
Let's watch a short video that introduces Feign Client and contrasts it with RestTemplate.
Microservice Communication Made Easy ! Feign Client in Spring Boot 🔥 @Javatechie
The video 'Microservice Communication Made Easy ! Feign Client in Spring Boot' by Java Techie provides a great overview of why Feign Client is a superior choice over RestTemplate for inter-service calls.
Watch the first few sections to understand the problem Feign solves: From 00:00 to 01:39: The introduction explains the boilerplate associated with RestTemplate. From 03:33 to 05:12: See an example of RestTemplate in action, which highlights the manual work involved. From 05:38 to 08:14: Watch how to add the Feign dependency and define a clean client interface.
2. Implementing the Feign Client in the Blog Service
Our goal is for the blog-service to call a validation endpoint on the auth-service. Let's assume our auth-service (which you would have built in Module 6) exposes an endpoint for this purpose.
Based on common patterns, this endpoint might look like: GET /api/v1/auth/validate?token={jwt}. It would return a 200 OK if the token is valid and a 401 Unauthorized or other error if it's not.
Let's now implement the client for this in our blog-service.
Step 1: Add OpenFeign Dependency
In your blog-service project, open the pom.xml file and add the spring-cloud-starter-openfeign dependency. You'll also need to ensure the Spring Cloud dependency management is in place.
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2023.0.1</version> <!-- Use a recent compatible version -->
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- ... other dependencies ... -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
After adding this, let your IDE sync the Maven project.
Step 2: Enable Feign Clients
Now, enable Feign client scanning in your main application class, BlogServiceApplication.java.
package com.blog.blogservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients; // Import this
@SpringBootApplication
@EnableFeignClients // Add this annotation
public class BlogServiceApplication {
public static void main(String[] args) {
SpringApplication.run(BlogServiceApplication.class, args);
}
}
This annotation tells Spring to scan for interfaces annotated with @FeignClient.
Step 3: Define the Feign Client Interface
- Create a new package named
com.blog.blogservice.client. - Inside this package, create a new Java interface named
AuthServiceClient.
This interface will declare the contract for calling the auth-service.
package com.blog.blogservice.client;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(name = "auth-service", url = "http://localhost:8081")
public interface AuthServiceClient {
@GetMapping("/api/v1/auth/validate")
void validateToken(@RequestParam("token") String token);
}
Let's break this down:
@FeignClient: This marks the interface as a Feign client.name = "auth-service": This is a logical name for the client. When we later integrate with a service discovery tool like Eureka, this name will be used to look up the service's address.url = "http://localhost:8081": For now, we are hardcoding the URL of theauth-service.
@GetMapping("/api/v1/auth/validate"): This annotation, along with the method signature, defines the request. Feign uses these annotations to construct the actual HTTP request.void validateToken(@RequestParam("token") String token):- The method will make a
GETrequest to/api/v1/auth/validate. - The
tokenparameter, annotated with@RequestParam("token"), will be added as a query parameter (e.g.,?token=...). - The return type is
voidbecause we only care if the call succeeds (2xx status) or fails (non-2xx status). A failure will automatically be translated into aFeignExceptionby Feign.
- The method will make a
3. Using the Feign Client to Secure an Endpoint
Now let's use our new AuthServiceClient to protect the endpoint for creating a post. We'll modify the PostController in the blog-service.
package com.blog.blogservice.controller;
import com.blog.blogservice.client.AuthServiceClient;
import com.blog.blogservice.dto.PostDto;
import com.blog.blogservice.service.PostService;
import feign.FeignException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
// ... other imports
@RestController
@RequestMapping("/api/v1/posts")
public class PostController {
private final PostService postService;
private final AuthServiceClient authServiceClient; // Inject the Feign client
public PostController(PostService postService, AuthServiceClient authServiceClient) {
this.postService = postService;
this.authServiceClient = authServiceClient;
}
// ... other methods like getPosts ...
@PostMapping
public ResponseEntity<PostDto> createPost(
@RequestBody PostDto postDto,
@RequestHeader(name = "Authorization", required = false) String authHeader) {
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Authorization header is missing or invalid");
}
String token = authHeader.substring(7);
try {
// Call the auth-service to validate the token
authServiceClient.validateToken(token);
} catch (FeignException.Unauthorized | FeignException.Forbidden e) {
// If auth-service returns 401 or 403, we throw 401
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid or expired token");
} catch (Exception e) {
// For other errors (e.g., auth-service is down), we return a server error
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Unable to verify token");
}
// If validation succeeds, proceed to create the post
PostDto createdPost = postService.createPost(postDto);
return new ResponseEntity<>(createdPost, HttpStatus.CREATED);
}
}
In this code:
- We inject our
AuthServiceClientvia constructor injection. - The
createPostmethod now accepts theAuthorizationheader via@RequestHeader. - We extract the JWT from the
Bearerscheme. - We wrap the call to
authServiceClient.validateToken(token)in atry-catchblock. This is our runtime debugging point!- If the
auth-servicereturns a401or403, Feign throws a correspondingFeignException. We catch this and return our own401 Unauthorizedto the client. - If the call succeeds, the code continues, and the post is created.
- If the
4. A More Elegant Solution: Token Relaying with RequestInterceptor
The manual approach above works, but it has a flaw: we are manually extracting the header and passing the token in every controller method that needs validation. This is repetitive and mixes security concerns with our controller logic.
A much cleaner, production-grade pattern is to automatically relay the token. We can configure Feign to intercept every outgoing request, grab the Authorization header from the original incoming request, and attach it to the Feign request.
For this, we use a RequestInterceptor.
Spring Cloud Feign implements JWT token relay to deliver ...
The article 'Spring Cloud Feign implements JWT token relay' explains exactly why manual token passing is problematic and how to use a RequestInterceptor to automate it. This is a key pattern in microservice security.
Please read through the article, paying close attention to these parts: Couldn’t the token be automatically relayed at Feign?: Understands why Feign doesn't do this by default, especially with fault tolerance enabled (ThreadLocal issues). InheritableThreadLocal: Explains the mechanism (RequestContextHolder) that makes the solution possible by passing request attributes to child threads. Implementing token relay: Shows the final code for the BearerTokenRequestInterceptor. This is the code we will implement.
Let's implement this superior approach.
-
Create a Feign Configuration Class: In the
blog-service, create a new configuration classcom.blog.blogservice.config.FeignClientConfig.package com.blog.blogservice.config; import feign.RequestInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; @Configuration public class FeignClientConfig { private static final String AUTHORIZATION_HEADER = "Authorization"; @Bean public RequestInterceptor requestInterceptor() { return requestTemplate -> { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (attributes != null) { String authHeader = attributes.getRequest().getHeader(AUTHORIZATION_HEADER); if (authHeader != null && authHeader.startsWith("Bearer ")) { requestTemplate.header(AUTHORIZATION_HEADER, authHeader); } } }; } } -
Update the Feign Client: Now, we must tell our
AuthServiceClientto use this configuration. We also need to change the endpoint we call. Instead of a custom/validateendpoint, we can call a standard, secured endpoint on theauth-servicethat requires authentication, like a hypothetical/api/v1/auth/meto get the current user's profile. The interceptor will automatically add the token, and if theauth-servicereturns a200 OK, we know the token is valid.Let's assume the
auth-servicehas an endpointGET /api/v1/auth/profilethat is secured and returns user details.Update
AuthServiceClient.java:package com.blog.blogservice.client; import com.blog.blogservice.config.FeignClientConfig; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; // Add the configuration to the annotation @FeignClient(name = "auth-service", url = "http://localhost:8081", configuration = FeignClientConfig.class) public interface AuthServiceClient { // We can define a simple validation method that hits any protected endpoint. // The interceptor will automatically add the Authorization header. @GetMapping("/api/v1/auth/validate-token") // Let's assume this is a simple protected endpoint void validateToken(); }Note: For this to work, the
auth-servicemust have a protected endpoint at/api/v1/auth/validate-token. If it doesn't, you can create a simple one that just returnsResponseEntity.ok().build();but is protected by your Spring Security configuration. -
Simplify the Controller: With the interceptor in place, our controller becomes much cleaner. We no longer need to handle the
Authorizationheader manually.@PostMapping public ResponseEntity<PostDto> createPost(@RequestBody PostDto postDto) { // The actual validation logic now happens inside Spring Security filter chain // which would use the Feign client. For simplicity in this lesson, // we will keep the explicit call but without manual header management. try { // The interceptor automatically adds the token from the incoming request. authServiceClient.validateToken(); } catch (FeignException.Unauthorized | FeignException.Forbidden e) { throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid or expired token"); } catch (Exception e) { throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Unable to verify token. Service may be down."); } PostDto createdPost = postService.createPost(postDto); return new ResponseEntity<>(createdPost, HttpStatus.CREATED); }Notice our
validateToken()method in the Feign client no longer takes any arguments, and our controller method doesn't need the@RequestHeader. The magic happens automatically in theRequestInterceptor.
Debugging Task: The 401 Cascade
You've deployed the token relay logic using the RequestInterceptor. The flow is:
- A client sends a request with a valid JWT to the gateway:
POST /posts. - The gateway forwards it to the
blog-service. - The
blog-service'screatePostmethod is invoked. - It calls
authServiceClient.validateToken(). - The
RequestInterceptoradds theAuthorizationheader to this outgoing Feign call. - Feign calls the
auth-service's protected endpoint (/api/v1/auth/validate-token).
However, the auth-service returns a 401 Unauthorized, which causes the blog-service to also return a 401. You've used a debugger and confirmed the RequestInterceptor is correctly adding the Authorization: Bearer ... header.
Question: Given that the token is valid and the header is being correctly relayed, what is the most likely configuration issue in the auth-service that would cause it to reject its own valid token when called from another service?
Click for the answer
The most likely issue is that the auth-service's Spring Security configuration is protecting all endpoints by default, including the ones needed for login and token generation (/api/v1/auth/token). When you added Spring Security, you might have forgotten to explicitly permit access to public endpoints.
In the auth-service's security configuration class (e.g., SecurityConfig.java), the securityFilterChain bean needs to specify which paths are public. A common mistake is to secure everything (.anyRequest().authenticated()) without whitelisting the auth-related endpoints themselves.
The correct configuration should look something like this:
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
// ... other configurations ...
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/api/v1/auth/register", "/api/v1/auth/token").permitAll() // Whitelist public endpoints
.anyRequest().authenticated() // Secure all other endpoints
);
// ...
return http.build();
}
The bug here isn't in the inter-service call itself, but in the security posture of the service being called. The auth-service is rejecting the request because the endpoint being called (/api/v1/auth/validate-token) requires authentication, but something in the security setup is preventing even valid tokens from being processed correctly, often because the filter chain is misconfigured for its own public endpoints, leading to a cascading failure. A key thing to check is if the endpoint that validates the token is itself being blocked by the security filter.
Conclusion
Excellent work! You have successfully implemented a critical microservices pattern: secure inter-service communication. You've gone from a naive manual implementation to a clean, professional solution using OpenFeign and a RequestInterceptor.
Key Takeaways:
- OpenFeign is a powerful declarative client that greatly simplifies service-to-service calls in Spring Cloud.
- The Token Relay pattern, implemented with a
RequestInterceptor, is the standard way to propagate authentication state across service boundaries without writing repetitive code. - By using
RequestContextHolder, the interceptor can access the original incoming request's headers, even when Feign calls are executed in different threads. - Securing microservices involves not just the gateway, but also ensuring that individual services can verify identity by communicating with a central auth service.
Preview of the Next Lesson:
Our services can now communicate, but they are all running as separate processes on our local machine. The next step towards a production-like environment is to add observability. In our next lesson, you will add health check endpoints to each microservice using Spring Boot Actuator. This is the first step in building a resilient system that can be monitored for health and availability.