0

In my Spring boot project, I have made some some RESTful APIs. Now, for each request in my APIs, I want to set a specific header like below below-

enter image description here

If the Http request is called with that specific header name and header value, only then it will show response code ok(200) otherwise it will show some other response code.

I need one single configuration to fix that specific header for each request in my project. So, I need some suggestion about the procedure to follow to solve this issue.

2
  • maybe this can help , you can use bareer token for your requests stackoverflow.com/questions/44977972/… Commented Feb 12, 2020 at 19:19
  • Just to clarify, are you wanting to validate the header in the req or add a header to your res? your 1st sentence suggests the former, but the 2nd suggests the latter. Commented Feb 12, 2020 at 20:58

1 Answer 1

2

I think in these kind of scenarios if you want to handle them in single point filters are good choices

I hope below code can give you the idea how to use filter to solve your problem:

import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class HeaderCheckerFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String header = request.getHeader("MyHeader"); if (header != null && header.equals("HeaderValue")) { filterChain.doFilter(request, response); } else { response.getWriter().println("invalid request"); } } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.