Skip to content

Instantly share code, notes, and snippets.

@juhahinkula
Created October 13, 2017 11:26
Show Gist options
  • Save juhahinkula/bdb25071fe42640bf5b72820afabe40f to your computer and use it in GitHub Desktop.
Save juhahinkula/bdb25071fe42640bf5b72820afabe40f to your computer and use it in GitHub Desktop.
CORS filter for Spring Boot
mport java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
@Component
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, xsrf-token");
response.addHeader("Access-Control-Expose-Headers", "xsrf-token");
if ("OPTIONS".equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(request, response);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment