Cross-Origin Request Blocked in Ionic/Laravel - 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

Related

SignalR connection failing when calling through an intermittent WebApi Service

I've an angular app, a gateway service(web api) and an asp.net core service(where the SignalR hub is present). I'm trying to connect from the angular app to SignalR hub through the gateway and the request is failing with the below error:
Access to XMLHttpRequest at '(gateway)/signalR/connect/negotiate' from origin '(UI website)' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
//UI code:
this is request I'm posting from angular app.
const connection = new signalR.HubConnectionBuilder()
.withUrl(https://gateway/signalr/connect)
.withAutomaticReconnect()
.build();
//Gateway code:
https://gateway/signalr/connect is a post api in gateway service.
With in the gateway post api, I'm making a connection to signalr hub like below:
https://localhost:19081/(myservice)/SignalR/(myHub)
//SignalR Service:
Also added the below cors policy in my signalr startup:
services.AddCors(options => options.AddPolicy("SignalRPolicy", builder =>
{
builder.AllowAnyHeader()
.AllowCredentials()
.AllowAnyMethod()
.WithOrigins(<allowedorigins>);
}));
app.UseCors("SignalRPolicy");
app.UseAzureSignalR(routes =>
{
routes.MapHub<HubClass>("/<myhub>");
});
If I directly call the SignalR hub from UI - this request is passing and connecting to signalr successfully.
Here both Gateway service and my signalr service are hosted on azure service fabric. The requirement is, all the calls from UI need to go through the gateway.
Please let me know how I can make this work. Thank you.
You must to explicit (withCredentials: false) at hub connection.
const connection = new signalR.HubConnectionBuilder()
.withUrl(https://gateway/signalr/connect,
{ skipNegotiation: false,
withCredentials: false,
transport: signalR.HttpTransportType.WebSockets })
.withAutomaticReconnect()
.build();

Blocked by CORS policy: Response to preflight request

Error:Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
ASP.NET MVC Core 3.1 API cors config:
services.AddCors(options => options.AddPolicy(CorsPolicy,
builder =>
{ builder
.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("https://www.hotff.com",
"https://www.hotff.com:44389","https://localhost:4200",
"http://localhost:4200","https://localhost:44371",
"http://localhost:4300","http://127.0.0.1:8080") //.AllowAnyOrigin()
.SetIsOriginAllowedToAllowWildcardSubdomains()
.AllowCredentials();
}));
This config works from Angular 8 client, no issue on port http://localhost
When the API is deployed on an IIS 10 server the request works from an Edge browser fine but not from Android or Chrome browsers. Tried all solutions I could find, read everything I could find.
I think the issue is the pre-flight request...

Ionicview and ionic serve CORS

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.

Clicking an href to our Github oAuth endpoint works, but an AJAX request to same endpoint gives a CORS error?

We are trying to implement Github oAuth in our app using Passport.js. If the user hits the endpoint by clicking an anchor tag/href, it works fine, but if we use a click handler to initiate an ajax request instead, we receive a CORS error from the Github server. Why?
Server side code:
app.get('/auth/github',
passport.authenticate('github', { scope: [ 'user:email' ] }));
app.get('/auth/github/callback',
passport.authenticate('github', { failureRedirect: '/login' }),
function(req, res) {
console.log('Github authentication successful!');
res.redirect('/');
});
Client side code (we are using React):
--> Works:
<a href='/auth/github'>Contact</a>;
--> Does Not Work - CORS error:
handleContactAuth(event) {
$.ajax({
url: '/auth/github',
method: 'GET',
success: data => console.log( 'Contact Auth response: ', data),
error: err => console.log( 'Error connecting to GitHub.', err)
});
}
NOTE: This is a click handler on the React component and is functioning fine, as the ajax request is being triggered. I'm aware we're not handling the response currently, apart from just a console.log.
--> CORS Error we see on the Client side when using AJAX method instead of href:
XMLHttpRequest cannot load https://github.com/login/oauth/authorize? response_type=code&redirect_uri=ht…auth%2Fgithub%2Fcallback&scope=user%3Aemail&client_id=our_client_code. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
Any ideas? Would appreciate any insights - many thanks.
CORS error is not an error returned by the server, but one triggered by the browser if the response doesn't contain HTTP headers signaling that cross-origin requests are allowed. The endpoint you are hitting obviously isn't designed to be accessed like this.
I had the same problem and I found that at least in Google Chrome XMLHttpRequest object is restricted to same origin policy. So you may need to stick to using an anchor tag.
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
Link: https://developer.chrome.com/extensions/xhr

ERR_INSECURE_RESPONSE

In my angular2 app I making a HTTPS post request to the API:
this.http.post('https://myhost.com/api/users/sign_in', body, { headers: contentHeaders })
.subscribe(
response => {.....
And I am getting "failed to load resource: net::ERR_INSECURE_RESPONSE"
Everything was fine with HTTP until I switched to HTTPS.
I am using self signed certificate for myhost.com.
In browser I am able to accept the certificate and make a request to the API. Could I resolve this also to make an API request via http.post from angular2 directly?

Resources