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
CodePudding user response:
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.
CodePudding user response:
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.