Ionicview and ionic serve CORS - asp.net-web-api

My ionic app is connecting to asp.net web api on azure. The API already allow all origin to access and the API_KEY header. However I am still getting Message
"The origin 'http://localhost:8100' is not allowed." on both Ionic serve and ionic view
Code in ionic app
var headers = new Headers();
headers.append('API_KEY', 'X-some-key');
headers.delete("Origin");
let options = new RequestOptions({ headers: headers});
return this.http.get(url, options);
request and response header when using ionic serve

Found the answer from here : CORS enabled but response for preflight has invalid HTTP status code 404 when POSTing JSON
The problem is backend doesn't have OPTIONS handler, added OPTIONS handler in web.config works.

Related

MAUI / Xamarin HttpClient on Android not sending Bearer Authorization Header on GET to API

Struggling with MAUI to send a GET call from Android device to an API that requires Bearer auth. Setting the Authorization header in the HttpClient like so:
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token);
However at the API endpoint, the Authorization header is not being received at all.
We have also tried sending an HttpRequestMessage with the Authorization header set explicitly, but still no dice.
It turned out the API we were sending to was running on both HTTP and HTTPS URLs.
In our android client config, we were sending to the HTTP URL.
Then we noticed that our API was set to redirect HTTP->HTTPS : app.UseHttpsRedirection();
So it turns out that Auth headers are stripped on redirect!
Authorization header is lost on redirect
When we changed our Android config to call the HTTPS URL directly, the Auth header started being received correctly.

API Gateway: Can't Enable CORS

I can't Enable CORS on my API Gateway instance, this is how it looks:
1. Settings:
2. Result:
I've tried a bunch of things like checking the DEFAULT 4XX and DEFAULT 5XX and manually inputting the Access-Control-Allow-Methods as suggested in some posts.
If I hover over the error I get: Invalid Response status code specified.
I'm able to GET using my browser but POST can only be done from Postman. My ReactJS website won't post either, throwing:
Access to XMLHttpRequest at <ENDPOINT> from origin <S3-REACT-BUCKET> has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I've read that I have my React app should send the CORS headers (haven't got to that) but I can't even Enable CORS in the API Gateway!
That was because No Method Response
You shouldn't manually go on the console to enable CORS. Instead follow this guide from the serverless framework.
In short:
set cors: true in your http event
return {'Access-Control-Allow-Origin': '*','Access-Control-Allow-Credentials': true} in your handler

Cross-Origin Request Blocked in Ionic/Laravel

Hi I am developing a Progressive Web App using Ionic and Laravel as API provider. My Ionic app is not loading data from a remote server using angular, and shows "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.1.5/restful_rain_forest/public/api1.0/slide. (Reason: missing token ‘x-xsrf-token’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel)".
My Angular code is as follows
this.http.get('http://192.168.1.5/restful_rain_forest/public/api1.0/slide').map(res => res.json()).subscribe(data => {
console.log(data);
this.posts = data;
},
err => {
console.log("Oops!");
});
Any help would be highly appriciated

How to make angular2 properly trigger the correct callback after successful preflight requests

In my angular2 app, I tried to make a cross domain ajax call. Although the call went through successfully, on angular2 side, the error callback was always triggered instead of the success callback. Here is the code:
this.http.post('http://localhost:3000/tasks/add', '["' + task + '"]', {headers: headers}).subscribe(
data => null,
err => alert("err"),
() => alert("succ")
);
In the browser console I saw this:
XMLHttpRequest cannot load http://localhost:3000/tasks/add. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
The server side was implemented in nodejs and it included the following to handle preflight
router.options('/add', (req, res, next) => {
console.log('!OPTIONS');
var headers = {};
// IE8 does not allow domains to be specified, just the *
// headers["Access-Control-Allow-Origin"] = req.headers.origin;
headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
headers["Access-Control-Allow-Credentials"] = false;
headers["Access-Control-Max-Age"] = '86400'; // 24 hours
headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
res.writeHead(200, headers);
res.end();
});
The above server code was successfully executed, and client side did send the post request after the preflight options request.
My question is, what can I do in angular2 to make it trigger the success callback, which it should?
Update:
I am attaching a screenshot here and it was took in Chrome. The bottom part of it shows CORS error message, but top portion shows that the request went okay with 200. As a matter of fact it did go through, as I received both the options and post requests on the server side.
Update 2:
Tried express-cors on nodejs (server) side, still the same. (My initial code already handles preflight options request - the code can be found above in the original portion of this post. Unless there was a mistake in my original nodejs code, express-cors was not expected to change anything.)
Below is the code I tried with express-cors, basically the same as what's on its npm page:
var express = require('express');
var cors = require('express-cors')
var router = express.Router();
router.use(cors({
allowedOrigins: [
'*'
]
}))
Update 3:
Mystery solved! In my original code I only set the CORS headers in the options response, but not the response to the post request followed the options request. That appeared to still allow the whole process to complete at the application level - since the server side did get the post request and processed the data, but angular saw an error since the response did not include the proper headers. I modified my code to not only send back CORS headers in the options response, but also the post response, and now angular triggers the success callback.
In fact, there is a dedicated module for CORS with Express called cors. You can install it like this: npm install cors.
That said, there is nothing to do in the browser since everything is done under the hood for cross domain requests:
The browser sends the Origin header
Use simple or preflighted requests
Check the CORS response headers to see if your request can be executed
This link could help you to understand how CORS works within browsers: http://restlet.com/blog/2015/12/15/understanding-and-using-cors/
So in short, it's a server issue not something in the Angular application. You can check the response content (headers) in the Chrome dev tools, tab Network to see that CORS headers are there in the response (both simple and preflighted).
Your error message doesn't look like the preflight request was successful. The preflight request is made by the browsers automatically before the actual request, if the preflight request results in an error, like in your case, the actual request isn't made at all.
Try this on the server instead:
headers["Access-Control-Allow-Origin"] = "http://localhost";

Error when adding vue http header

I have a working application with a front end in vuejs and a backend in go. I'm in the process of adding the final features to the authentication and I'm running into an error.
When I try to add any http header to the vuejs request I get an error.
This is what I'm adding to the vue component:
http: {
headers: {
Authorization: 'Bearer 123'
}
}
And I'm getting a preflight error:
XMLHttpRequest cannot load http://localhost:8000/api/investments?limit=6. 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:8080' is therefore not allowed access.
Now I know this is usually a server side problem but I am adding the response header resp.Header().Set("Access-Control-Allow-Origin", "*"). cors. If I remove the the http property in the vue object everything works fine. Its pretty bizzare I even tried handling the OPTIONS request with go but my handler for the api doesn't even get hit.
Ok so I found the answer it is a server problem the Authorization header was not authorized. So just add it as a middleware to allow for it.
c := cors.New(cors.Options{
AllowedHeaders: []string{"Origin", "Accept", "Content-Type", "Authorization"},
})
handler := c.Handler(router)
log.Fatal(http.ListenAndServe(":8000", handler))
I am using the rs/cors package

Resources