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.

Saeed Alizadeh
  • 1,417
  • 13
  • 23
S. M. Asif
  • 3,437
  • 10
  • 34
  • 58
  • maybe this can help , you can use bareer token for your requests https://stackoverflow.com/questions/44977972/how-to-enable-bearer-authentication-on-spring-boot-application – Guillermo Nahuel Varelli Feb 12 '20 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. – Nate T Feb 12 '20 at 20:58

1 Answers1

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");
        }
    }
}
Saeed Alizadeh
  • 1,417
  • 13
  • 23