I want to make a React.js app that can interact with Odoo and its endpoints in a secure way while allowing to have the auth flag set to user and cors enabled.
For this I've set an endpoint like this:
#http.route('/endpoint', type='json', auth="user", cors="*")
def endpoint(self, **params):
This works with no problem when I post with axios from React.js with auth set to none but I want to keep user authentication, and if I do keep it with user="auth" I get the following.
Access to XMLHttpRequest at 'http://localhost:8069/endpoint' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
I don't understand, I have the cors flag in the endpoint and I'm sending in the headers the session_id that the authenticate method gives me.
"Content-Type": "application/json",
Accept: "application/json",
"X-Openerp-Session-Id": Cookies.get("session_id"),
I've tried many things but none has yield a good result. Is there no way to tell Odoo through a header that I'm a real user outside a template rendered by its engine? While keeping cors enabled (which apparently I haven't been able to do regardless of what the official documentation tells me) and an auth flag to keep the data secure?
Related
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.
I needed to use the StackOverflow API to retrieve some data from the site. Actually, when I tried the first time to use the API I got an exception due to CORS policy.
Access to fetch at 'https://stackoverflow.com/users/myID/reputation'
from origin 'http://localhost:3000' has been blocked by CORS policy:
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.
I understand that the reason why my request was blocked was that the header was not in the response. However, does not StackExchange API attach in the response header Access-Control-Allow-Origin? I'm doing something wrong in how I'm invoking the request?
does not StackExchange API attach in the response header Access-Control-Allow-Origin? I'm doing something wrong in how I'm invoking the request?
The Stack Exchange API permits client-side requests, but the page you're requesting is not the Stack Exchange API - it's just a plain Stack Exchange page, not the API endpoint designed for such things, so it doesn't have the required header.
If you want to use the API properly, go through the documentation here and choose the endpoint you need. For an example using my user ID, one might use the following code:
fetch('https://api.stackexchange.com/2.2/users/9515207/reputation?site=stackoverflow')
.then(res => res.json())
.then(console.log);
api.stackexchange.com has the proper headers: access-control-allow-origin: *, which allows for client-side scripts to request it.
since this request is for a trial project, can I implement a proxy using a free-tier of some platform? I see a lot of suggestions for Heroku but I'm not very familiar with that platform
For the more general case of a server that doesn't set the required headers, if you wanted to use one of their responses client-side, you would have to bounce the request off a relay server. You could either make your own app on Heroku (a good free option), or use something like https://cors-anywhere.herokuapp.com/
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.
I succesfully installed "JWT Authentication for WP REST API" and followed (and reviewed multiple times) the instructions for setup correctly.
My React app does authenticate via the /jwt-auth/v1/token-endpoint.
I get a token back and store this in my localStorage.
All of my API-calls get added an authorization header as follows from this point on:
Authorization: Bearer mYCust0mToken
In the browser, this triggers preflight requests to the server (which is a remote one), that all fail. Basically logging in kills all of my API-requests.
I'm now getting 405's stating the following:
Access to fetch at
'https://mywebpage.com/wp-json/wp/v2/posts/'
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.
I run WP inside a subdir, so I have two .htaccess files, one in the root, one in the wp/-directory. I've tried putting the suggested .htaccess-changes of the descriptions in both files, on several positions of the file, but still no luck.
I've also tried setting Allow-Origin headers to "*", just for the sake of testing. I did that in both the .htaccess-files, but also in my PHP.
Anyone out there that got "JWT Authentication for WP REST API" up and running and willing to tell how?
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]