1

I'm caught in a situation where I need to manually add a header(Authorization) to the request.

The catch is that I only need to add that header to requests coming to a specific API(Controller). Not to all.

I'm using Java 1.8 with Spring Boot.

Is there anyway to achieve this?

I want to achieve this : Image description

PseudoDev
  • 11
  • 7

2 Answers2

1

This might work for you..

public class MyCustomFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
    if(httpServletRequest.getRequestURI().equals("Your custom URI")){
        httpServletResponse.setHeader("Authorization","Your value");
    }
    filterChain.doFilter(httpServletRequest,httpServletResponse);
}
}

For every request, checks the URI and if matches,adds the Authorization header.Also, you will probably need to add @Component annotation.

  • Thanks Vasilis. I'll try this. Btw I am already using OncePerRequestFilter for JWT authentication for my Application. Is it fine to use multiple OncePerRequestFilter or should I just implement this on same old filter? – PseudoDev May 08 '22 at 04:37
  • I am not really sure, but I suppose you can implement it on same OncePerRequestFilter. – Tsimpragakis Vasilis May 09 '22 at 11:26
0

I guess that this is the answer that you are looking for:

@RequestMapping(value = "/users", method = RequestMethod.GET)
public List<AppUser> getUsers(OAuth2Authentication auth, @RequestHeader (name="Authorization") String token) 

More info here is the reference of this code: https://stackoverflow.com/a/54911059/13842927

I hope that this helped you.

Sanady_
  • 68
  • 10
  • Thanks for the effort but in my case user's not setting header from the UI. It must set at the backend somehow. – PseudoDev May 06 '22 at 07:59
  • Your welcome, but API is a two-way street, you send something and you get a response, so if your user sign-in it gets a token as a response which you are saving in the cookies or session or in whatever way. So please specify your problem with more details :) – Sanady_ May 06 '22 at 08:01
  • To be more specific, the API on to which I need to add header is provided by a 3rd party dependency(java-melody). So when I hit that URL from browser I need to add header of authorization token manually on backend. I am also attaching an image. Please follow updated question. – PseudoDev May 06 '22 at 08:43