SimpleCORSFilter not working - ajax

I am using Spring Rest as my backend, when I sent request by $.ajax{}, I got error message:
XMLHttpRequest cannot load http://121.40.249.129:8080/user/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access.
So, I added SimpleCORSFilter in my Spring Project:
SimpleCORSFilter:
#Component
public class SimpleCORSFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version");
chain.doFilter(req, res);
}
#Override
public void init(FilterConfig filterConfig) {}
#Override
public void destroy() {}
}
The since I don't have web.xml, so I didn't add the code to web.xml:
<filter>
<filter-name>simpleCORSFilter</filter-name>
<filter-class>xxx.xxx.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>simpleCORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
So, I still get the error, how can I fix it.

As I have experienced, * won't work for Access-Control-Allow-Origin when Access-Control-Allow-Credentials is set to true.
So, you should instead have
response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8000");
Actually, instead of hardcoding the url, you can have that as a property. If you want to allow multiple origins, this answer would help.
Also:
It's advised to annotate the class with #Order(Ordered.HIGHEST_PRECEDENCE), because this filter should come first.
If you are using CSRF, the corrosponding header should also be added to the list in Access-Control-Allow-Headers.
Update:
As #RTzhong did (see his comments below), replacing * with request.getHeader("Origin") seems like the ideal fix. However, a better security practice in general would be to specify the actual url or first checking with a whitelist, unless one must expose his API publicly to unknown websites.
Refer to Spring Lemon's source code for a concrete example.

Related

How to forbid `DELETE` http request in Springboot?

The security department ask us to forbid DELETE and some other http request method if we don't need to use it in our applications. In SpringMVC I can add the security-constraint in web.xml like this:
<security-constraint>
<display-name>delete-method</display-name>
<web-resource-collection>
<web-resource-name>unsafe-method</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>DELETE</http-method>
</web-resource-collection>
<auth-constraint/>
But I don't know how to add in Springboot. The server is tomcat8.x and run at CentOS.
You can use CORS filter for it. You cas specify allowed HTTP request types there.
Example from the Spring docs:
<mvc:cors>
<mvc:mapping path="/api/**"
allowed-origins="http://domain1.com, http://domain2.com"
allowed-methods="GET, PUT"
allowed-headers="header1, header2, header3"
exposed-headers="header1, header2" allow-credentials="false"
max-age="123" />
<mvc:mapping path="/resources/**"
allowed-origins="http://domain1.com" />
</mvc:cors>
OR
You can do it with Java.
Here's the nice implementation
#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, 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);
}
}
}

Invalid CORS request in Spring

I am trying to enable certain IPs to access a particular method.
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/updateDetail")
.allowedOrigins("127.0.0.1", "10.96.33.45")
.allowedMethods("GET", "POST");
}
But when I am trying to call the same method I am getting invalid CORS request. Can anyone help me with this?
"Invalid CORS request" is returned by org.springframework.web.cors.DefaultCorsProcessor when
Spring is configured to use CORS and
browser sends "Origin" header with the request and it does not match with your server domain/port/scheme and
response does not have "Access-Control-Allow-Origin" header and
the request is not a preflight request.
If you don't need CORS, call cors().disable() in your implementation of WebSecurityConfigurerAdapter#configure(HttpSecurity http) (there might be other ways to do this, for example if you use Spring Boot).
Or you could add "Access-Control-Allow-Origin" header to your reponses using e.g. org.springframework.web.cors.CorsConfiguration or addCorsMappings (like you did, but maybe you should add more methods or url or IP doesn't match?).
This class is what are you looking for:
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCorsFilter implements Filter {
public SimpleCorsFilter() {
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "12000");
response.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
response.setHeader("Access-Control-Expose-Headers", "*");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
#Override
public void init(FilterConfig filterConfig) {
}
#Override
public void destroy() {
}
}
This filter will resolve all your cors issues
I was debugging problem like this for few days. The actual problem was that I had typo in my service uri name /data vs. /daba etc. This cause SpringBoot to fail to retrieve CORS configuration (even when I had /** mapping) so CORS-preflight got status 403, which caused browser not to make the actual request at all - if browser would have fired the request, Spring would have returned "Resource not found" and then I would have noticed the typo much faster.
if you started your application at localhost, the browser formulates the origin as null, so application will not get the origin localhost:8080 or 127.0.0.1, it will get null
I think changing 127.0.0.1 with null will fix your problem
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/updateDetail")
.allowedOrigins("null", "10.96.33.45")
.allowedMethods("GET", "POST");
}

Extending SpringBootWebSecurityConfiguration with custom HttpSecurity configuration

I am trying to gain a better understanding of the auto-configuration of spring boot. In particular I need to add some custom spring security configuration to disable authentication for HTTP OPTIONS verbs in order to get my CORS requests working.
Without any custom configuration by default the SpringBootWebSecurityConfiguration is loaded by Spring Boot's auto-configuration.
What I would like to do is to keep using this auto-configuration but add some additional http configuration. I tried this:
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
Logger logger = LogManager.getLogger (SecurityConfiguration.class);
#Override
protected void configure (HttpSecurity http) throws Exception {
logger.info ("--- ALLOW all HTTP OPTIONS Requests");
http.authorizeRequests ().antMatchers (HttpMethod.OPTIONS, "*//**").permitAll ();
}
}
But this does not work as excepted. When I debug through SpringBootWebSecurityConfiguration and also the above code, I can see that both my configure-method and springs auto-configuration are executed but it looks like my http-configuration takes precedence.
So does that mean the auto-configuration is available only in an all-or-nothing kind of way? Or can I use the the auto-configuration but still extend it with some custom antMatcher?
What is the best-practice for this scenario?
You could create a new servlet filter and place it before the Spring security filter. For example:
#Component("CORSFilter")
public class CORSFilter implements Filter {
public void doFilter(
ServletRequest req,
ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Origin", "THE_HOST_YOU_WANT_TO_ALLOW_HERE");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, PATCH, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"origin, content-type, accept, x-requested-with, authorization");
if (request.getMethod().equals("OPTIONS")) {
try {
response.getWriter().print("OK");
response.getWriter().flush();
} catch (IOException e) {
//...
}
} else {
chain.doFilter(req, res);
}
}
public void init(FilterConfig filterConfig) {
//...
}
public void destroy() {
//...
}
}
and then add this to your web.xml (or configure in your WebInitializer if you are using Java config only):
<filter>
<filter-name>CORSFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>contextAttribute</param-name>
<param-value>org.springframework.web.servlet.FrameworkServlet.CONTEXT.[YOUR_SERVLET_NAME]</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The reason you cannot do it is you are missing the annotation #EnableWebSecurity, have a look at the javadoc:
* Add this annotation to an {#code #Configuration} class to have the Spring Security
* configuration defined in any {#link WebSecurityConfigurer} or more likely by extending
* the {#link WebSecurityConfigurerAdapter} base class and overriding individual methods:

Spring - Resteasy - Cors Double Access-Control-Allow-Origin header in response

I setup a web application with Spring 3 and Resteasy; since my resources require authentication I am not allowed to use * as Access-Control-Allow-Origin.
So I configured
org.jboss.resteasy.plugins.interceptors.CorsFilter
with the right origin domain.
This works with a desktop client (Paw for Mac Os and others), but not with the browser (Chrome); the problem is that the response contains a double value for Access-Control-Allow-Origin, that is the one I configured and '*'.
CorsFilter is not to blame because, even if you configure more than one origin, it always puts just one value for the header, the one which the request asked for.
I simply have no idea on who's putting that extra (and wrong) header, any idea on where I could look for?
Please note that the double header occurs on GET requests but not on OPTIONS requests.
I'm not sure where your doubled header comes from, but did you try to use custom filter?
e.g. :
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCorsFilter implements Filter {
public SimpleCorsFilter() {
}
#Override
public void doFilter(ServletRequest req,
ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Authorization, Content-Type");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
#Override
public void init(FilterConfig filterConfig) {
}
#Override
public void destroy() {
}
}
I finally found out there is a proprietary MessageBodyWriterInterceptor in the classpath which does a wrong add header; now it's on me to remove that.
One thing I learned is that if something happens only when there is a body to write, a good starting point is surely the rendering pipeline
I've tried the following actions and it worked as a charm:
First, register the CorsFilter provider class in your web.xml:
<context-param>
<param-name>resteasy.providers</param-name>
<param-value>org.jboss.resteasy.plugins.interceptors.CorsFilter</param-value>
</context-param>
By doing so, your server is already enabled to handle CORS requests, however, you need to add some allowed origins to get it working, therefore, you should get access to the CorsFilter's instance, which was created by RestEasy then add all the URLs you wish to grant access to or add a * if you wish to grant access to any.
In this regard, if you're using RestEasy Spring Integration, you'll need to grab an instance of the org.jboss.resteasy.spi.ResteasyProviderFactory class by autowiring it into your code:
#Autowired
private ResteasyProviderFactory processor;
then use a setup method annotated with #PostConstruct to get the instance of the CorsFilter from the ResteasyProviderFactory like the code snippet below:
#PostConstruct
public void setUp() {
ContainerRequestFilter[] requestFilters = processor.getContainerRequestFilterRegistry().preMatch();
CorsFilter filter = (CorsFilter) Iterables.getLast(Iterables.filter(Arrays.asList(requestFilters), Predicates.instanceOf(CorsFilter.class)));
filter.getAllowedOrigins().add("*");
}
P.S.: I'm using this frameworks:
Spring Framework 3.2.18.RELEASE
RestEasy 3.0.12.Final
I hope it helps!
For those struggling like me who don't use the Application starter but only Spring + Reasteasy.
Just add in web.xml:
<context-param>
<param-name>resteasy.providers</param-name>
<param-value>package.to.your.cors.CORSFilter</param-value>
</context-param>
And create the Java Class CORSFilter like
package package.to.your.cors;
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
#Provider
public class CORSFilter implements ContainerResponseFilter {
#Override
public void filter(final ContainerRequestContext requestContext,
final ContainerResponseContext cres) throws IOException {
cres.getHeaders().add("Access-Control-Allow-Origin", "*");
cres.getHeaders().add("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
cres.getHeaders().add("Access-Control-Allow-Headers", "X-Auth-Token, Content-Type");
cres.getHeaders().add("Access-Control-Max-Age", "4800");
}
}
It works like a charm.
PS: inspired by s_bighead answer but I could not comment his answer to add my details.

Spring 4.2.2 CORS Support not working

#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
}
I'm following the guide in https://spring.io/blog/2015/06/08/cors-support-in-spring-framework and added the above code to my WebConfig
However, CORS is not working, log show
20151103 183823 [http-bio-8080-exec-3] WARN org.springframework.web.servlet.DispatcherServlet (DispatcherServlet.java:1136) - No mapping found for HTTP request with URI [/my/url] in DispatcherServlet with name 'dispatcher'
I can successfully call my api without CORS(same domain), so it is not the api problem.
In Chrome console, log show
XMLHttpRequest cannot load http://localhost:8080/my/url.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 404.
Just add this filter for CROS in package which is contain other configuation
#Component
public class RequestFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {
}
public void destroy() {
}
}
It will work fine for you.

Resources