Antoine Grenard
Antoine Grenard

Reputation: 1892

Spring MVC : retrieve Http Request header

I implemented a micro-services architecture. Before accessing each micro-service the request gets through a gateway that checks the authentication and in the process adds an X-User header containing the user id.

In each of my micro-services, I would like to be able to retrieve this user (X-User) in an elegant way: without adding the HttpRequest/@RequestHeader to all my Controllers and pass it to the services, etc.

Using something like "SecurityContextHolder.getContext().getAuthentication().getUserId();" would be perfect but as I don't manage the Authentication in my micro services it's not possible.

Upvotes: 1

Views: 500

Answers (1)

Jamie Bisotti
Jamie Bisotti

Reputation: 2675

You should be able to:

  1. implement a Servlet Filter (see this Baeldung article for details) that gets the userId from the ServletRequest and stores it in a ThreadLocal (see this Baeldung article for details)
  2. retrieve that ThreadLocal from any class that would need the userId

Good luck!

Upvotes: 1

Related Questions