Access-Control-Allow-Origin error for cross platform - ajax

Hi I am trying to post some information on ajax call with cross domain. unfortunately i am getting below error.
XMLHttpRequest cannot load http://prodservices.apps.h2radio.com:8080/util-services/contributor/feedback. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://rivetnewsradio.com' is therefore not allowed access
I have searched for the above error and i have integrated below code in filter.
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");
response.setHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with, my-cool-header");
response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, res);
even I am getting same error i don't know how to resolve it. can any one give me the trick to get on.

* won't work as Access-Control-Allow-Origin When Access-Control-Allow-Credentials is set to true. So, try specifying the exact base URL, e.g. http://localhost:9000.
Instead of hardcoding the URL, you could use a property. If multiple sites could access your server, then a common practice is to get the site's base URL dynamically and checking it against a whilelist. I have it like this:
String origin = request.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin",
ArrayUtils.contains(properties.getAllowedOrigins(), origin) ?
origin : properties.getDefaultApplicationUrl());
It wouldn't be considered a good practice, but if you must allow all URLs, just replace the * with request.getHeader("Origin").

Related

Access-Control-Allow-Headers header not being added in response for cors non simple request?

For the non simple cors request i am adding the following headers.
def testPostJSON(){
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
response.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
render request.JSON.name
}
But you can see Access-Control-Allow-Headers is missing in the response headers. What is the reason it is missing? I am using Grails 2.2 for the server. Thanks for help!
This plugin solved the problem.
https://grails.org/plugin/cors

Response for preflight has invalid HTTP status code 403 + angular 2 + Java Spring boot

I am making an API GET call to the server with following headers in angular 2. My angular 2 code is as follows:
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', `${this.publisherAccessTokenVar}`);
let options = new RequestOptions({ headers: headers });
return this.http.get( 'https://blahblah', options)
.retryWhen((error) => error.delay(this.appConfig.serviceCallRetryDelay))
.timeout(this.appConfig.serviceCallRetryTimeOut)
.map((response: Response) => response.json());
MY spring boot CORS code is as follows:
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", ((HttpServletRequest) req).getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST,PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Access-Control-Request-Method,Access-Control-Request-Headers,Content-Type, Accept, X-Requested-With, remember-me, Authorization, X-XSRF-TOKEN");
chain.doFilter(req, res);
I am getting following error:
OPTIONS http://blah-blah.com/abcd/logout 403 (Forbidden)
XMLHttpRequest cannot load http://blah-blah.com/abcd/logout. Response for preflight has invalid HTTP status code 403
How to solve this??
you have to add #CrossOrigin before your controller declaration .

Http OPTION REQUEST with cors in web api with authentication

I am using Microsoft.AspNet.WebApi.Cors to support cross origin request as per this
https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
My web apis are configured to use windows authentication and every request coming from angular has withCredentials set to true. Everything is working with HTTP GET but with PUT request sends preflight request which in getting unauthorised. My question is does Microsoft.AspNet.WebApi.Cors support configuration of OPTION request.
Put this in your Global.asax.cs
(I'm sure you either found a solution or gave up, but this is the link that I found on Google while looking for a solution to this.)
protected void Application_BeginRequest()
{
if (Request.HttpMethod == "OPTIONS")
{
Response.StatusCode = (int)HttpStatusCode.OK;
Response.AppendHeader("Access-Control-Allow-Origin", Request.Headers.GetValues("Origin")[0]);
Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
Response.AppendHeader("Access-Control-Allow-Credentials", "true");
Response.End();
}
}

Sending ajax request between https

I'm using angular to send ajax request to nodejs file, and I'm having this error,
XMLHttpRequest cannot load https://localhost:3000/SetUser. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost' is therefore not allowed access.
sending it from index.html to https://localhost:3000/SetUser, and direction what could go wrong and how can I allow that access of Access-Control-Allow-Origin?
-- edit:
I googled and I found this lines
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
but I still get the same error, this is the current app.post
app.post('/SetUser', function(req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
console.log("New user added ", req.body);
});
thanks!

HTTP OPTIONS error in Phil Sturgeon's Codeigniter Restserver and Backbone.js

My backbone.js application throwing an HTTP OPTIONS not found error when I try to save a model to my restful web service that's located on another host/URL.
Based on my research, I gathered from this post that :
a request would constantly send an OPTIONS http request header, and not trigger the POST request at all.
Apparently CORS with requests that will "cause side-effects on user data" will make your browser "preflight" the request with the OPTIONS request header to check for approval, before actually sending your intended HTTP request method.
I tried to get around this by:
Settting emulateHTTP in Backbone to true.
Backbone.emulateHTTP = true;
I also allowed allowed all CORS and CSRF options in the header.
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
The application crashed when the Backbone.emulateHTTP line of code was introduced.
Is there a way to respond to OPTIONS request in CodeIgniter RESTServer and are there any other alternatives to allow either disable this request from talking place?
I found this on Github as one solution. I am not sure if I should use it as it seems a bit outdated.
I encountered exactly the same problem. To solve it I have a MY_REST_Controller.php in core and all my REST API controllers use it as a base class. I simply added a constructor like this to handle OPTIONS requests.
function __construct() {
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if($method == "OPTIONS") {
die();
}
parent::__construct();
}
This just checks if the request type is OPTIONS and if so just dies out which return a code 200 for the request.
You can also modify the $allowed_http_methods property in your subclass to exclude the options method. Previous versions of REST_controller did nothing with OPTIONS and adding this line seems to mimic that behavior:
protected $allowed_http_methods = array('get', 'delete', 'post', 'put');
I solved in this way:
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, x_requested_with");
if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
die();
}
Pay attention to add x_requested_with in Access-Control-Allow-Headers.

Resources