0

I have a Spring Boot web application that expects all incoming requests to have a cookie with a valid JWT ID token. The ID token holds the email address of the user, which is used to query the database for the User entity. The User entity is then used by multiple services.

Currently, the controllers receive the raw ID token as a parameter, and then passes it down to the services:

@PostMapping()
void foo(@CookieValue String rawIdToken) {
  myService.bar(rawIdToken);
}

Then each service is parsing the token and querying the database:

void bar(String rawIdToken) {

  // Parse the ID token
  IdToken idToken = IdToken.from("RAW_ID_TOKEN");

  // Query the database
  User user = userRepository.findByEmail(idToken.getEmail());

  // Code that requires the User entity..
}

Is there a way to avoid having to do this every time, and instead automatically make the User entity available to all controllers? So that, for example, the sample controller above can become something like that:

@PostMapping()
void foo(User user) {
  myService.bar(user);
}

And the service:

void bar(User user) {
  // Code that requires the User entity..
}

Please let me know if I am looking at this the wrong way.

Gimmi
  • 11
  • 1
  • 2

1 Answers1

1

You can create a Filter. This Filter gets the User from DB and add it to session as attribute. Then you can take the User object from session by httpRequest.getAttribute()

Here is about creating filter: https://www.baeldung.com/spring-boot-add-filter

It is about setting ang getting session object: Spring: how to pass objects from filters to controllers

Alper Derya
  • 237
  • 1
  • 9
  • 1
    I might be wrong, but it seems like the filter only processes the request without modifying it? In your second link, I see that the accepted answer uses a @Bean with the "request" scope - that seems like it would work, but I am not sure how that would work with final fields. – Gimmi Mar 30 '22 at 16:16
  • No, you can use filter to set/get attribute to request. The first link I sent is about getting something from request but it is OK to add new attribute on it. By the way, the accepted answer in second link is not first and most thumbed up answer. It is another answer which has 15 likes on the discussion. Two of them are applicable. It is up to you but my answer was about using Filter. Using Request Scope Bean could be nice. – Alper Derya Mar 31 '22 at 08:13