Last active
October 4, 2022 11:44
-
-
Save zeroows/80bbe076d15cb8a4f0ad to your computer and use it in GitHub Desktop.
To enable CORS support in Spring MVC 4 - Access-Control-Allow-Origin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.alkhodiry.mb.rest.filters; | |
import java.io.IOException; | |
import javax.servlet.FilterChain; | |
import javax.servlet.ServletException; | |
import javax.servlet.http.HttpServletRequest; | |
import javax.servlet.http.HttpServletResponse; | |
import org.apache.commons.logging.Log; | |
import org.apache.commons.logging.LogFactory; | |
import org.springframework.web.filter.OncePerRequestFilter; | |
/** | |
* Enabling CORS support - Access-Control-Allow-Origin | |
* @author [email protected] | |
* | |
* <code> | |
<!-- Add this to your web.xml to enable "CORS" --> | |
<filter> | |
<filter-name>cors</filter-name> | |
<filter-class>com.elm.mb.rest.filters.CORSFilter</filter-class> | |
</filter> | |
<filter-mapping> | |
<filter-name>cors</filter-name> | |
<url-pattern>/*</url-pattern> | |
</filter-mapping> | |
* </code> | |
*/ | |
public class CORSFilter extends OncePerRequestFilter { | |
private static final Log LOG = LogFactory.getLog(CORSFilter.class); | |
@Override | |
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { | |
response.addHeader("Access-Control-Allow-Origin", "*"); | |
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) { | |
LOG.trace("Sending Header...."); | |
// CORS "pre-flight" request | |
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); | |
// response.addHeader("Access-Control-Allow-Headers", "Authorization"); | |
response.addHeader("Access-Control-Allow-Headers", "Content-Type"); | |
response.addHeader("Access-Control-Max-Age", "1"); | |
} | |
filterChain.doFilter(request, response); | |
} | |
} | |
Great! Thank you so much.
Gracias funciono muy bien
thank you so much . its work for me
Thanks, It helped me :)
XML Config also can do the same thing at Spring 4.2.x
Spring Doc
Where shall we put that class?
Funiona ! me ha salvado el dia gracias.
Thank you so much. You saved my day !!!!!!
Awesome...
is it really needed?
Spring has its own configuration: https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/cors.html
As well as Tomcat: https://tomcat.apache.org/tomcat-8.0-doc/config/filter.html#CORS_Filter
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not working for me. I am unable to allow Authorization Header