HTTPS Request : CORS error but I still get data - javascript

I'm making HTTPS request to a private API (hosted Itop), I get an response but I get CORS Multiple Origin Not Allow error so my JavaScript program can't use the response content.
I'm supposed to have CORS authorization
The requests are POST, made with fetch, there isn't preflight (OPTIONS) request made before (fetch did them alone for my other GET API request but didn't here)
Also some server response time is long for firefox (~2s) but it don't seems to change anything

It's not allowed to send multiple Access-Control-Allow-Origin headers or multiple origins in one header in the same response. In the comments, you described two same Access-Control-Allow-Origin headers in one response. Even two same origins aren't allowed. Remove one header in the backend code.

firefox is the best browser to identify this issue,
you can fix this issue by following this path.
when you sending a request from frontend,and then response will come from backend. but browser is not allowed to aceess to javascript. this is the cors error.
1.open ur backend, then create a package call CorsFilter.
2. and then create a filter servlet
3. paste this code
CorsFilter
#WebFilter(filterName = "CorsFilter", urlPatterns = "/*")
public class CorsFilter extends HttpFilter {
#Override
protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
String origin = req.getHeader("Origin");
if (origin != null && origin.toLowerCase().contains(getServletContext().getInitParameter("origin"))) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
res.setHeader("Access-Control-Expose-Headers", "Content-Type");
if (req.getMethod().equals("OPTIONS")) {
res.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE, HEAD");
}
}
chain.doFilter(req, res);
}
}

Related

unable to set 'Access-Control-Allow-Origin' header

I need to access my web api hosted remotely from my react app. On the server side i did below to allow cross domain communication:
import javax.ws.rs.core.Response;
import com.mypackage.ResponseDto;
#Override
public Response fetch(String id, String env) throws ServiceException
{
ResponseDto res = new ResponseDto();
res = updateResp(id, env); // not important
return Response.ok().header("Access-Control-Allow-Origin","*").entity(res).build();
}
When i check from postman i can see cors header correctly set as below:
access-control-allow-origin →*
content-type →application/json
date →Wed, 16 Aug 2017 11:07:16 GMT
server →web
transfer-encoding →chunked
But when i access the same endpoint from react app, browsers starts complaining with below error:
Fetch API cannot load
http://myservices.com/myservice-app/services/. 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:3000' is therefore not allowed
access. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled
Any idea whats going on here?
Edit#1
Did below change still see the same error:
return Response.ok()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS")
.header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With")
.entity(response).build();
I have no experience with whatever Java library you're using, but something like this must work:
#Override
public Response options() throws ServiceException
{
ResponseDto res = new ResponseDto();
return Response.ok().header("Access-Control-Allow-Origin","*").entity(res).build();
}
If the library works like I think it does, this will send a 200 OK on every OPTIONS request you send to your server, with header Access-Control-Allow-Origin = *. That's what you should be aiming for.

JavaScript add CORS to jersey [duplicate]

I'm developing a java script client application, in server-side I need to handle CORS, all the services I had written in JAX-RS with JERSEY.
My code:
#CrossOriginResourceSharing(allowAllOrigins = true)
#GET
#Path("/readOthersCalendar")
#Produces("application/json")
public Response readOthersCalendar(String dataJson) throws Exception {
//my code. Edited by gimbal2 to fix formatting
return Response.status(status).entity(jsonResponse).header("Access-Control-Allow-Origin", "*").build();
}
As of now, i'm getting error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.”
Please assist me with this.
Thanks & Regards
Buddha Puneeth
Note: Make sure to read the UPDATE at the bottom. The original answer includes a "lazy" implementation of the CORS filter
With Jersey, to handle CORS, you can just use a ContainerResponseFilter. The ContainerResponseFilter for Jersey 1.x and 2.x are a bit different. Since you haven't mentioned which version you're using, I'll post both. Make sure you use the correct one.
Jersey 2.x
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
#Provider
public class CORSFilter implements ContainerResponseFilter {
#Override
public void filter(ContainerRequestContext request,
ContainerResponseContext response) throws IOException {
response.getHeaders().add("Access-Control-Allow-Origin", "*");
response.getHeaders().add("Access-Control-Allow-Headers",
"CSRF-Token, X-Requested-By, Authorization, Content-Type");
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS, HEAD");
}
}
If you use package scanning to discover providers and resources, the #Provider annotation should take care of the configuration for you. If not, then you will need to explicitly register it with the ResourceConfig or the Application subclass.
Sample code to explicitly register filter with the ResourceConfig:
final ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.register(new CORSFilter());
final final URI uri = ...;
final HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(uri, resourceConfig);
For Jersey 2.x, if you are having problems registering this filter, here are a couple resources that might help
Registering Resources and Providers in Jersey 2
What exactly is the ResourceConfig class in Jersey 2?
Jersey 1.x
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;
#Provider
public class CORSFilter implements ContainerResponseFilter {
#Override
public ContainerResponse filter(ContainerRequest request,
ContainerResponse response) {
response.getHttpHeaders().add("Access-Control-Allow-Origin", "*");
response.getHttpHeaders().add("Access-Control-Allow-Headers",
"CSRF-Token, X-Requested-By, Authorization, Content-Type");
response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHttpHeaders().add("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS, HEAD");
return response;
}
}
web.xml configuration, you can use
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>com.yourpackage.CORSFilter</param-value>
</init-param>
Or ResourceConfig you can do
resourceConfig.getContainerResponseFilters().add(new CORSFilter());
Or package scanning with the #Provider annotation.
EDIT
Please note that the above example can be improved. You will need to know more about how CORS works. Please see here. For one, you will get the headers for all responses. This may not be desirable. You may just need to handle the preflight (or OPTIONS). If you want to see a better implemented CORS filter, you can check out the source code for the RESTeasy CorsFilter
UPDATE
So I decided to add a more correct implementation. The above implementation is lazy and adds all the CORS headers to all requests. The other mistake is that being that it is only a response filter, the request is still processes. This means that when the preflight request comes in, which is an OPTIONS request, there will be no OPTIONS method implemented, so we will get a 405 response, which is incorrect.
Here's how it should work. So there are two types of CORS requests: simple requests and preflight requests. For a simple request, the browser will send the actual request and add the Origin request header. The browser expects for the response to have the Access-Control-Allow-Origin header, saying that the origin from the Origin header is allowed. In order for it to be considered a "simple request", it must meet the following criteria:
Be one of the following method:
GET
HEAD
POST
Apart from headers automatically set by the browser, the request may only contain the following manually set headers:
Accept
Accept-Language
Content-Language
Content-Type
DPR
Save-Data
Viewport-Width
Width
The only allowed values for the Content-Type header are:
application/x-www-form-urlencoded
multipart/form-data
text/plain
If the request doesn't meet all of these three criteria, a Preflight request is made. This is an OPTIONS request that is made to the server, prior to the actual request being made. It will contain different Access-Control-XX-XX headers, and the server should respond to those headers with its own CORS response headers. Here are the matching headers:
REQUEST HEADER
RESPONSE HEADER
Origin
Access-Control-Allow-Origin
Access-Control-Request-Headers
Access-Control-Allow-Headers
Access-Control-Request-Method
Access-Control-Allow-Methods
XHR.withCredentials
Access-Control-Allow-Credentials
With the Origin request header, the value will be the origin server domain, and the response Access-Control-Allow-Origin should be either this same address or * to specify that all origins are allowed.
If the client tries to manually set any headers not in the above list, then the browser will set the Access-Control-Request-Headers header, with the value being a list of all the headers the client is trying to set. The server should respond back with a Access-Control-Allow-Headers response header, with the value being a list of headers it allows.
The browser will also set the Access-Control-Request-Method request header, with the value being the HTTP method of the request. The server should respond with the Access-Control-Allow-Methods response header, with the value being a list of the methods it allows.
If the client uses the XHR.withCredentials, then the server should respond with the Access-Control-Allow-Credentials response header, with a value of true. Read more here.
So with all that said, here is a better implementation. Even though this is better than the above implementation, it is still inferior to the RESTEasy one I linked to, as this implementation still allows all origins. But this filter does a better job of adhering to the CORS spec than the above filter which just adds the CORS response headers to all request. Note that you may also need to modify the Access-Control-Allow-Headers to match the headers that your application will allow; you may want o either add or remove some headers from the list in this example.
#Provider
#PreMatching
public class CorsFilter implements ContainerRequestFilter, ContainerResponseFilter {
/**
* Method for ContainerRequestFilter.
*/
#Override
public void filter(ContainerRequestContext request) throws IOException {
// If it's a preflight request, we abort the request with
// a 200 status, and the CORS headers are added in the
// response filter method below.
if (isPreflightRequest(request)) {
request.abortWith(Response.ok().build());
return;
}
}
/**
* A preflight request is an OPTIONS request
* with an Origin header.
*/
private static boolean isPreflightRequest(ContainerRequestContext request) {
return request.getHeaderString("Origin") != null
&& request.getMethod().equalsIgnoreCase("OPTIONS");
}
/**
* Method for ContainerResponseFilter.
*/
#Override
public void filter(ContainerRequestContext request, ContainerResponseContext response)
throws IOException {
// if there is no Origin header, then it is not a
// cross origin request. We don't do anything.
if (request.getHeaderString("Origin") == null) {
return;
}
// If it is a preflight request, then we add all
// the CORS headers here.
if (isPreflightRequest(request)) {
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS, HEAD");
response.getHeaders().add("Access-Control-Allow-Headers",
// Whatever other non-standard/safe headers (see list above)
// you want the client to be able to send to the server,
// put it in this list. And remove the ones you don't want.
"X-Requested-With, Authorization, " +
"Accept-Version, Content-MD5, CSRF-Token, Content-Type");
}
// Cross origin requests can be either simple requests
// or preflight request. We need to add this header
// to both type of requests. Only preflight requests
// need the previously added headers.
response.getHeaders().add("Access-Control-Allow-Origin", "*");
}
}
To learn more about CORS, I suggest reading the MDN docs on Cross-Origin Resource Sharing (CORS)
Remove annotation "#CrossOriginResourceSharing(allowAllOrigins = true)"
Then Return Response like below:
return Response.ok()
.entity(jsonResponse)
.header("Access-Control-Allow-Origin", "*")
.build();
But the jsonResponse should replace with a POJO Object!
The other answer might be strictly correct, but misleading. The missing part is that you can mix filters from different sources together. Even thought Jersey might not provide CORS filter (not a fact I checked but I trust the other answer on that), you can use tomcat's own CORS filter.
I am using it successfully with Jersey. I have my own implementation of Basic Authentication filter, for example, together with CORS. Best of all, CORS filter is configured in web XML, not in code.
peeskillet's answer is correct. But I get this error when refresh the web page (it is working only on first load):
The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://127.0.0.1:8080' is therefore not allowed access.
So instead of using add method to add headers for response, I using put method. This is my class
public class MCORSFilter implements ContainerResponseFilter {
public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
public static final String ACCESS_CONTROL_ALLOW_ORIGIN_VALUE = "*";
private static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
private static final String ACCESS_CONTROL_ALLOW_CREDENTIALS_VALUE = "true";
public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
public static final String ACCESS_CONTROL_ALLOW_HEADERS_VALUE = "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With, Accept";
public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
public static final String ACCESS_CONTROL_ALLOW_METHODS_VALUE = "GET, POST, PUT, DELETE, OPTIONS, HEAD";
public static final String[] ALL_HEADERs = {
ACCESS_CONTROL_ALLOW_ORIGIN,
ACCESS_CONTROL_ALLOW_CREDENTIALS,
ACCESS_CONTROL_ALLOW_HEADERS,
ACCESS_CONTROL_ALLOW_METHODS
};
public static final String[] ALL_HEADER_VALUEs = {
ACCESS_CONTROL_ALLOW_ORIGIN_VALUE,
ACCESS_CONTROL_ALLOW_CREDENTIALS_VALUE,
ACCESS_CONTROL_ALLOW_HEADERS_VALUE,
ACCESS_CONTROL_ALLOW_METHODS_VALUE
};
#Override
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
for (int i = 0; i < ALL_HEADERs.length; i++) {
ArrayList<Object> value = new ArrayList<>();
value.add(ALL_HEADER_VALUEs[i]);
response.getHttpHeaders().put(ALL_HEADERs[i], value); //using put method
}
return response;
}
}
And add this class to init-param in web.xml
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>com.yourpackage.MCORSFilter</param-value>
</init-param>
To solve this for my project I used Micheal's answer and arrived at this:
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<id>run-embedded</id>
<goals>
<goal>run</goal>
</goals>
<phase>pre-integration-test</phase>
<configuration>
<port>${maven.tomcat.port}</port>
<useSeparateTomcatClassLoader>true</useSeparateTomcatClassLoader>
<contextFile>${project.basedir}/tomcat/context.xml</contextFile>
<!--enable CORS for development purposes only. The web.xml file specified is a copy of
the auto generated web.xml with the additional CORS filter added -->
<tomcatWebXml>${maven.tomcat.web-xml.file}</tomcatWebXml>
</configuration>
</execution>
</executions>
</plugin>
The CORS filter being the basic example filter from the tomcat site.
Edit:
The maven.tomcat.web-xml.file variable is a pom defined property for the project and it contains the path to the web.xml file (located within my project)

Interaction between application deployed in two different domain in GWT

I have an application which contains the UI code created as WAR (GWT application) and server side code as EAR deployed in two different domains(8080,9090) respectively. While communicating from 8080to9090 its sending a request and even i can see its returning the response 200. But the client is throwing some GWT exception **Permission denied to access property 'document' **. Below image shows the exception thrown in fire bug.
Note: i have enabled the CORS in server 9090 see the below code added in server side code EAR
#Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest) arg0;
HttpServletResponse response=(HttpServletResponse) arg1;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
arg2.doFilter(request, response);
}
Is there any think i need to add in GWT client UI to handle this exception.Any suggestion ?
It seems, that you trying to make AJAX GWT-RPC request on the different domain/port? Even if you try to "cheat" it, it won't work in all browsers (it won't be cross-browser), because CORS is rather new solution that came with HTML5.
Maybe you should consider using REST protocol to communicate between Client and Server?
I had such problem when I had to communicate between different domain context from UI to Server and the only way was to use REST service. Cross browser solution.
If you want still to stick with breaking SOP and applying CORS try to change your filter according to this article: https://code.google.com/archive/p/gwtquery/wikis/Ajax.wiki
Like this:
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;
String origin = req.getHeader("Origin");
if (origin != null && origin.matches(ALLOWED_DOMAINS_REGEXP)) {
resp.addHeader("Access-Control-Allow-Origin", origin);
if ("options".equalsIgnoreCase(req.getMethod())) {
resp.setHeader("Allow", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS");
if (origin != null) {
String headers = req.getHeader("Access-Control-Request-Headers");
String method = req.getHeader("Access-Control-Request-Method");
resp.addHeader("Access-Control-Allow-Methods", method);
resp.addHeader("Access-Control-Allow-Headers", headers);
// optional, only needed if you want to allow cookies.
resp.addHeader("Access-Control-Allow-Credentials", "true");
resp.setContentType("text/plain");
}
resp.getWriter().flush();
return;
}
}
// Fix ios6 caching post requests
if ("post".equalsIgnoreCase(req.getMethod())) {
resp.addHeader("Cache-Control", "no-cache");
}
if (filterChain != null) {
filterChain.doFilter(req, resp);
}
}
And don't forget to configure the filter properly:
<filter>
<filter-name>CORSFilter</filter-name>
<filter-class>my.namespace.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

CORS issue for Scalable application

I have three applications followed by authserver, resource server and front end application in AngularJS. The AngularJS application is running on the Node Server and the other resources are running on Tomcat Server. Through AngularJS using CORS I am able to login to authserver (http://localhost:8081/oauth/token) and I am unable to access resource server (http://localhost:8082/api/devices). The headers are adding like this:
var config = {
headers: {
'Authorization': 'bearer '+authToken,
'Accept': 'application/json;odata=verbose'
}
};
$http.get(RESOURCE_SERVER + 'api/devices',config).then(function(response){
console.log(""+response.data);
});'''
The headers are not adding to the resource server and getting the exception like CORS issue. My main concern is I am able to login to auth server but not to resource server why it like this?
#Component
public class SimpleCORSFilter 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, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
Error : : XMLHttpRequest cannot load http://192.168.0.130:8080/golive-resource/api-docs. The
'Access-Control-Allow-Origin' header contains multiple values '*, *',
but only one is allowed. Origin 'http://127.0.0.1:9000' is therefore
not allowed access.
The problem is that somewhere else in your setup you are also setting the Access-Control-Allow-Origin header and rather than one overwriting the other they get combined by the server, meaning you end up with two values.
Having two values for this header results in an error. You should therefore find out where else you are setting this header and either remove that instance or remove it from your snippet above.
Actually browser makes preflight request before your actuall request with http request method "options" . so you have to send 200 OK to this request
if(httpRequest.getMethod().equals("OPTIONS")){
httpResponse.setStatus(HttpServletResponse.SC_ACCEPTED);
return;
}
More information you can find at http://enable-cors.org/

CORS in grails - All requests fail?

I'm trying to setup CORS support in grails, and I'm using the following filter:
class CorsFilters {
def filters = {
all(controller:'*', action:'*') {
before = {
response.setHeader("Access-Control-Allow-Origin", "*")
}
}
}
}
From testing, it looks like the response header is set properly for all requests, but when I make a request externally against localhost or some server available to me, I get the following error:
XMLHttpRequest cannot load http://server:8080. Origin http://jsbin.com is not allowed by Access-Control-Allow-Origin.
This live example works in my instance of Chrome, so I don't know what could be happening here. In the requests that fail, I'm trying to hit tomcat directly.
What could be happening to cause this to fail?
It looks like Grails Filters, by default, run too late in the filter chain to be of use.
If you generate the web.xml template and add a filter beneath sitemesh, this works.
<filter>
<filter-name>CORSFilter</filter-name>
<filter-class>com.blah.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
and
class CorsFilter implements Filter {
public void init(FilterConfig fConfig) throws ServletException { }
public void destroy() { }
public void doFilter(
ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
((HttpServletResponse) response).addHeader(
"Access-Control-Allow-Origin", "*"
)
chain.doFilter(request, response)
}
}
You can set the origin dynamically. I also recommend to add the whole set of headers when applies.
response.setHeader('Access-Control-Allow-Origin', request.getHeader("Origin"))
response.setHeader('Access-Control-Allow-Methods', 'POST, PUT, GET, OPTIONS, PATCH')
response.setHeader('Access-Control-Allow-Headers', 'X-Additional-Headers-Example')
response.setHeader('Access-Control-Allow-Credentials', 'true')
response.setHeader('Access-Control-Max-Age', '1728000')
Access-Control-Allow-Origin should contain exact domain name (btw, for some browsers '*' works as well), jsbin.com at your case.

Categories

Resources