cors problem with react js request and jwt - reactjs

i'm trying to fetch data with react from asp.net core 3.1 so i login with a request and get the jwt token. after that i want to send a request for getting data from api but it cause "preflight request "Access to fetch at 'https://localhost:44328/Address' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
apiAddress.js:24 GET https://localhost:44328/Address net::ERR_FAILED", i work with visual studio localhost as api server and configured startup like below:
//in ConfigureServices
services.AddCors(options =>
{
options.AddPolicy(name: AllowedOrigins,
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(hostName => true);
});
});
//in configure
app.UseCors(AllowedOrigins);
my fetch request is like below in reactjs:
const response = await fetch(url, {
'method': 'GET',
'mode': 'cors',
'credentials': 'include',
'headers': {
'Content-Type': 'application/json; charset=utf-8;',
//'Content-Type':'application/x-www-form-urlencoded',
'Authorization':`bearer ${token}`
}
});
and finally my controller is like below:
[ApiController, EnableCors("AllowedOrigins"), Authorize, Route("[controller]")]
public class AddressController : ControllerBase
what is wrong, i must mention other actions without [Authorize] attribute working ok, but action with it not works?!
some one mentioned that i should enable options in iis, but didn't explained how?

You will probably need to enable CORS on IIS. Here are steps how to do.
Open Internet Information Service (IIS) Manager.
Right click the site you want to enable CORS for and go to Properties.
Change to the HTTP Headers tab.
In the Custom HTTP headers section, click Add.
Enter Access-Control-Allow-Origin as the header name.
Enter * as the header value.
Click Ok twice.

Response to preflight request doesn't pass access control check: ....
other actions without [Authorize] attribute working ok, but action with it not works
In this doc, you would find:
A CORS preflight request is used to determine whether the resource being requested is set to be shared across origins by the server. And The OPTIONS requests are always anonymous, server would not correctly respond to the preflight request if anonymous authentification is not enabled.
While hosting on IIS server, you can try to install the IIS CORS module and configure for the site/application to make it work well.
Besides, if you'd like to make it work on local with IIS express, for testing purpose on CORS, you can try to allow anonymous access.
Or run it with kestrel and write custom middleware to correctly respond to the preflight request.

Related

CORS Error happens in api-key request in react js

I want to get api_kye and I use moqui framework in backend , use axios in react js project :
axios.get(SERVER_URL + '/rest/api_key', {
headers: {
Authorization: "Basic " + btoa(username + ":" + password) ,
'Content-Type' : 'application/x-www-form-urlencoded' ,
},
}).then(response => {})
then , when requested the below error happened :
Access to XMLHttpRequest at '...' from origin '...' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value '...' that is not equal to the supplied origin.
This is not a reactJS error, this is a problem with your backend code, you need to look at the Moqui docs to see how you can allow the origin you are calling from to access your API
Enable CORS in the server side
Let's head back to our server's app.js file.
app.get('/cors', (req, res) => {
res.set('Access-Control-Allow-Origin', '*');
res.send({ "msg": "This has CORS enabled 🎈" })
});
Also check the redirect URL in server side
Refer this link
when ever you send an HTTP request to an API the server response should include your domain in response header otherwise chrome will raise this error: "Access to XMLhttprequest has blocked for origin ...."
so first of all make sure that your domain is included in server code.
if it's included already then the reason could be that server can't process your response correctly. maybe it crashed so the response is corrupted and chrome can't find your domain in response header and it raises that error
So i have a solution for this but you may or may not be able to build it.
CORS is a security feature, you should be receiving requests thru your backend and not the browser directly in general...
IF the data is not sensitive and you want to open an endpoint to the world without getting CORS errors you can do one of two things
Set the CORS headers from the server side. You'll need to understand HTTP requests and headers. you set these from the server. enabling cross origin with * will work.
Build a proxy. I've done this in AWS API gateway, I'll link another post. works good. basically AWS will act as your back end and take the response with CORS blocked. you will then proxy the request and strip the CORS header. When you call the api you will actually call AWS which calls the API, then AWS will pass the response back to you with CORS enabled.
Angular No 'Access-Control-Allow-Origin'
just follow these steps and it will work.

Why does CORS not make a request?

I have a problem with a CORS request
Access to fetch at 'https://webhook.site/f9087e12-b444-4e6b-9e64-06ba47b8c24e' from origin 'https://localhost:5001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
My request:
fetch("https://webhook.site/f9087e12-b444-4e6b-9e64-06ba47b8c24e", {
method: 'get',
headers: new Headers({
'Access-Control-Allow-Origin': 'https://localhost:5001',
'Content-Type': 'application/json;charset=utf-8'
}),
})
.then(res => res.json())
.then(
(result) => {
console.log('res ' + result);
},
(error) => {
console.log('error ' + error);
}
)
I can’t figure out how to solve the problem.
CORS is a server side thing. Your browser is contacting webhook.site and saying "I want to download that thing f9087e12-b444-4e6b-9e64-06ba47b8c24e, what domains will you serve it to?" and webhook.site is saying e.g. "I'll only serve it to scripts that were downloaded from whatever.com" and your browser is thinking "hmm, well the script making the request was downloaded from localhost so.. denied"
You need to change the webhook.site server so it has an allow for localhost, not the client. It is the server response to the OPTIONS request that must contain the Access-Control-Allowed-Origin header, not the request from the client. Or you need to make the request without CORS in which case the browser will not make the options request.
CORS headers shall be returned from the server.
The server behind https://webhook.site/f9087e12-b444-4e6b-9e64-06ba47b8c24e shall return the header 'Access-Control-Allow-Origin': 'https://localhost:5001' in response to all requests, especially the OPTIONS request (preflight).
Best intro to the subject I have seen is https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
In a nutshell, the server shall decide if it allows CORS in general and to what resources.
The browser is responsible to protect the user by obeying to the rules defined by the server.
Hope it is helpful...
This is a browser's way of protecting it's users. Your request may be innocent, but imagine a scenario where the user goes to an innocent looking website which then uses http to send any password a user inputs to a thief. So the browser will only allow requests to the same domain or "origin".
There are ways around it, but the commonly accepted practice is to send the request to your server (localhost:5001) and your server sends a request to the other site and sends the response back to the browser.
That way all requests go through the domain that the user decided to trust by visiting.

How to properly setup the barryvdh/laravel-cors in reactjs

I am currently new in ReactJS and facing problem regarding getting the response of API the console log shows of error of this
Access to XMLHttpRequest at 'https://facebook.github.io/react-native/movies.json' from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
they recommend to me that I use the barryvdh/laravel-cors to allow the cors in my API. I will show you guys my front-end code.
componentDidMount() {
axios.get('https://facebook.github.io/react-native/movies.json',{
}).then(function(response){
console.log(response)
})
}
In my logs, I will share here the captured image.
The error is in your Axios request itself, if you clearly see
axios.get('https://facebook.github.io/react-native/movies.json',{})
You've an additional parameter, While you are not passing any headers or other parameters, if you remove the {} then it should work.
axios.get('https://facebook.github.io/react-native/movies.json')
And if you see the results of your console you can see on where it clearly states that OPTIONS request is throwing a 405 status code,
from MDN
The HyperText Transfer Protocol (HTTP) 405 Method Not Allowed response
status code indicates that the request method is known by the server
but is not supported by the target resource.
You'll need to directly access the resource, probably your axios is generating Pre Flight Request with OPTIONS header due to {}, which is being rejected by the resource itself.
You can also try doing it with a simple fetch request,
fetch('https://facebook.github.io/react-native/movies.json')
.then(function(response) {
console.log(response.json())
})
CORS is controlled by backend API and in your case, you don't have control over it which is
https://facebook.github.io/react-native/movies.json.
Browser prevents your code from accessing the response because of the browser can't see Access-Control-Allow-Origin in response.
Things can still get working by making the request through a Proxy can where a proxy sends appropriate CORS header on behalf of your request.
const proxy = "https://cors-anywhere.herokuapp.com/";
const url = "https://facebook.github.io/react-native/movies.json";
fetch(proxy + url)
.then(response => response.text())
.then(contents => console.log(contents))
.catch(() => console.log("CORS Error" + url ))
Making a request through a proxy will work this way
CORS proxy will forward your request to https://facebook.github.io/react-native/movies.json
Return response from https://facebook.github.io/react-native/movies.json with Access-Control-Allow-Origin headers.
Now your browser can see Access-Control-Allow-Origin headers present in the response header.
For more detail explanation you can check out this
https://stackoverflow.com/a/43881141/2850383

Get method is converted to OPTIONS when hitting fetch api in React js

I am trying to hit below api and requires basic auth username and password and method allowed in this is only get
dispatch(requestBegin());
let apiPath = `xxxx/TEST/appservice/api/app/10/10000127201901`;
return fetch(apiPath, {
method: 'get',
headers : {
"contentType":"application/x-www-form-urlencoded",
"Authorization" : 'Basic '+btoa('xxx:xxx'),
},
})
.then((response) => {
dispatch(getEventsEnds(json));
})
.catch((error) => {
dispatch(getEventsEnds());
});
The error loged in console :
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:2200' is therefore not allowed
access. The response had HTTP status code 405. If an opaque response
serves your needs, set the request's mode to 'no-cors' to fetch the
resource with CORS disabled.
OPTIONS http://xxx/appservice/api/app/10/10000127201901 405 (Method
Not Allowed)
Can anyone please eplain when i m trying to hit get api then why is it showing options
That means your API server does not accept CORS request or requests originating from localhost.
Check out your API documentation but my guess is you won't be able to interact directly with it from your web app.
Your best bet is to use a proxy, you can develop one yourself or use something like node-http-proxy to proxy your API calls. (There are php or python equivalents)
The proxy server will be able to issue the requests and will then forward them to your app.
Suggested further reading: type understanding CORS on google and read more about it.
For local development, check out:
https://github.com/Rob--W/cors-anywhere
This issue occurs when the client api URL and server URL don't match, including the port number. In this case you need to enable your service for CORS which is cross origin resource sharing.
use npm install cors
refer this[refer][1]

Salesforce and Angular with separate servers

I have two sets of servers:
apache serving up html/js/css pages in the angular flavor
SalesForce backend rest apis serving up Json
Salesforce has OAuth authentication, but it is not letting the javscript even perform an OPTIONS call in order to figure out if it can do the POST call it really wants to:
Is there any way to get around this without a proxy or jsonp?
is the Salesforce APEX Rest API configured wrong? the source domain is already whitelisted...
Update:
so some angular code to make the call:
var config = {
method: 'POST',
url: SalesforceRestApi,
headers: {
Authorization: "OAuth "+authToken,
"Content-Type": "application/pdf"
},
data : caseRequest,
};
var http = angular.element(document.body).injector().get('$http');
http(config).then(function(response){ console.log(response); });
this code here returns the good old Chrome error:
XMLHttpRequest cannot load https://xxx.salesforce.com/services/apexrest/xxx/v1/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://sample.com' is therefore not allowed access. The response had HTTP status code 401.

Resources