browser extension - CORS proxy error using axios [duplicate] - vue.js

This question already has answers here:
How does the 'Access-Control-Allow-Origin' header work?
(19 answers)
Closed 2 years ago.
I'm using GimmeProxy api to get a proxy that I want to use in my vue chrome extension. Unfortunately I get this error:
Access to XMLHttpRequest at 'https://gimmeproxy.com/api/getProxy?get=true&supportsHttps=true&anonimityLevel=1&protocol=http' from origin 'chrome-extension://eamofepokjbdhndoegnmcnmgjhefhhlh' 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.
This is the code I have in my vuex action:
fetchProxyData({ commit }) {
axios({
method: 'get',
baseURL: 'https://gimmeproxy.com/api/getProxy',
params: {
get: true,
supportsHttps: true,
anonimityLevel: 1,
protocol: 'http'
},
headers: {
'Access-Control-Allow-Origin': '*'
}
}).then( (response) => {
console.log(response)
})
Is there a way to fix this?

In your code example, you are attempting to send the CORS headers from the client to the server.
It needs to be the other way around.
The client needs to respond to your request with the 'Access-Control-Allow-Origin': '*' header for this to work.
Can your check, using Chrome Dev tools network tab, that the server is returning the correct access control headers from the GimmeProxy API.
Edit: Upon further inspection, I don't seem to see an access control header on this API endpoint.
What you'll need to do in that case, is set up your own API endpoint as a middleman:
Set up an Express API on a VPS (or alternatively an AWS lambda function).
Create an endpoint that makes a request to gimmeproxy.
Your Chrome extension makes a request to this endpoint via Axios.
The endpoint makes a request to the gimmeproxy API via Axios (it is not a browser, so no cross origin policies are enforced).
Your API returns the response to the client.
It is important to note, that your Express API must return the header 'Access-Control-Allow-Origin': '*' or have an origin matching that of your extension.

Related

api request has been blocked by CORS policy

In my next.js project I'm trying to send a POST request using axios:
axios.defaults.baseURL = "https://{my-server-url}/api";
useEffect(() => {
axios({
method: "POST",
url: "/build_pages",
data: {
page_id: 3,
},
}).then((res) => {
console.log(res.data);
});
}, []);
I'm getting the following CORS error:
My server is [laravel] php and is deployed on cpanel, but before I deployed my backend to cpanel (i.e. when I was working on localhost) I did not get this error.
How do I turn off this error (note that I don't want to download any web browser extension to fix the CORS error)
I came across this link but it does not say where (which file) to add it to so I'm stuck
Edit: I tried the middleware solution provided in this answer: https://stackoverflow.com/a/69151121/12009071 but also it didn't work, howerver the error changed to:
Access to XMLHttpRequest at 'https://{my-server-url}/api/check_admin_login' from origin 'https://{my-server-url}.vercel.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
This is an API-side error. You have to allow cross origin requests on the API server. Based on your question, I assume your API is NOT the Next.js project.
Therefore, you should check the settings of your server. The next.js POST call is not the issue.

Fixed : Preflight Response Error : Access-control-allow-origin is not allowed by Access-Control-Allow-Headers for Express Lambda with AWS API Gateway [duplicate]

This question already has an answer here:
Access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response
(1 answer)
Closed 2 years ago.
I have prepared an Lambda function using Express(node.js) and enabled the Authorization with IAM as well.
The API is working in the Postman as per below link :
https://www.youtube.com/watch?v=KXyATZctkmQ&t=35s
As I'm fairly new with CORS policy and API concepts. I'm trying to access the sample using Ajax call.
So far I have prepared the Authorization Header as per documentation and few reference.
Git Repo Link : https://github.com/mudass1r/aws-iam-authorization.git
Reference Link for Signature Generation :
https://gist.github.com/davidkelley/c1274cffdc0d9d782d7e
I have Enabled the CORS from AWS API Gateway for my API as well.
PS : The API is Deployed using Serverless Framework.
Step 1 : The error I'm facing initial when I dont include any headers:
Step 2 : Later when I add headers:
$.ajax(Signer(credentials, {
url: <AWS API URL>,
type: 'GET',
dataType: 'json',
async: true,
crossDomain: true,
contentType: 'application/json',
headers: {
"Access-Control-Allow-Origin" : "*"
},
success: function(data) {
console.log(data);
}
}));
After which I get the following error:
In my previous experience with this error we only need to enable the CORS for the API which resolves this issue. But the same is not in this cases. Following is the structure of the API resource.
I have been stuck in this problem for few day and came across some CORS policy reference links as well.
https://fetch.spec.whatwg.org/#http-cors-protocol
Solution :
Refer : Access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response
Thanks for your help in advance.
There are a few things to look at here.
Make sure that all resposnes from within your Lambda function are returning cors headers. I see that is the case in your example.
Make sure that the function itself is not returning an error. You can see this in the Serverless Framework dashboard if you are using that or CloudWatch. If so, you need to find a fix or catch the error and make sure the response also includes the required CORS headers
Otherwise, if your Authorization is returning a 403, for example, you will need to configure the responses for API Gateways 4XX responses in the resources section of your serverless.yml, since API Gateway by default does not apply cors to authorizer responses. Something like:
resources:
Resources:
GatewayResponseDefault4XX:
Type: 'AWS::ApiGateway::GatewayResponse'
Properties:
ResponseParameters:
gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
gatewayresponse.header.Access-Control-Allow-Headers: "'*'"
ResponseType: DEFAULT_4XX
RestApiId:
Ref: 'ApiGatewayRestApi'

how to skip Preflight Requset in vue with content-type:application/json

error :"405 not allowed Method" in post method type call in request command vue
i need call api function with content-type:application/json and post Method type with request command in vue ,but browser add preflight request with options method type and it causes this error :"405 not allowed Method"
var options = {
method: "POST",
url: "http://api.sample.com/login",
headers: {
"Access-Control-Request-Method":"POST",
"cache-control": "no-cache",
"content-type": "application/json",
},
body: '{ Username: "demo", Password: "demo", Domain: "test" }'
};
request(options, function(error, response, body) {
if (error) throw new Error(error);
body.data;
alert("ok");
});
The OPTIONS call is done whenever you do a cross-origin request. This means the domain your application is running on is different from the domain where the api is. A pre-flight request is mandatory for these requests, because the browser needs to figure out if you are allowed to do these requests. A 405 error means that the server thinks you are not allowed to make that request.
To solve this problem you can move your api to the same domain as your frontend. Please note that it cannot be on a subdomain.
A different way of solving this, is by sending back the correct headers. In your case you seem to at least miss the Access-Control-Allow-Methods response header. Make sure to send this header and either dynamically figure out which methods are allowed, or do something like the following. That would allow the most common methods to work.
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
In the comments you said that you do not have control over the api, and as such cannot change the response header. In that case your best bet is to contact whoever maintains the api and ask how to best use their api.
In the comments you said that this worked fine when you did the same thing in ASP.NET. ASP.NET is a server-side language, which means that requests in that context do not have a concept of "cross-origin". Cross-origin only comes into play in the browser, where the application runs on an actual domain.
Assuming you can set up a proxy on your application domain, you can also create a proxy that proxies all requests to the api you actually want to communicate with. You would deploy your domain on https://example.com and do your requests to https://example.com/api/endpoint. Your proxy will listen for requests that begin with https://example.com/api and proxy it to https://whatever.the.api.is/ with the appropriate endpoint and data.
Please keep in mind that while some api's might just be configured incorrectly, a lack of cross-origin response headers might just mean that the api is nog meant to be consumed through the browser. Part of this could be that the request contains a secret that should not be exposed to users that use your application, but should instead only be on the server. Using a proxy in that case would set you up for impersonation attacks, because you would expose the secret to your application, but defeat the cross-origin headers by making it appear to the application that the api is on the same domain.

Moqui REST API call fail with error code 403

From my Angular 2 application I am trying to get data from Moqui but the request always fails with the error code 403.
Here is the REST API call implementation
getExample() {
let url = 'http://localhost:8080/rest/s1/example/examples'
let headers = new Headers({ 'Authorization': 'Basic
am9obi5kb2U6bW9xdWk='});
headers.append('Accept', 'application/json, text/plain, */*');
headers.append('Content-Type', 'application/json; charset=UTF-8');
let options = new RequestOptions({ headers: headers });
let response = this.http.get(url, options).map(res => res.json());
return response;
}
The Moqui logs :-
REST Access Forbidden (no authz): User null is not authorized for View on REST Path /example/examples
There is also a similar question Moqui Rest Nginx but from the answer I do not know that where I have to change the settings in Moqui.
On the client console the error is :-
XMLHttpRequest cannot load http://localhost:8080/rest/s1/example/examples. Response for preflight has invalid HTTP status code 403
But with a rest client like YARC it works :-
You must authenticate for REST API calls except for Service REST API paths that are configured to not require authentication (like the /mantle/my end points in the mantle.rest.xml file in the mantle-usl component).
You have authentication but then there is one other step: authorization. In general if authc is required then authorization is also required. This is done with database records usually either in seed data and can also be added using the System app that is included in the default Moqui runtime (ie the moqui/moqui-runtime repository).
There is an example of authorization setup for Service REST API calls in the MantleSetupData.xml file. The main difference from screen authorization is that the artifact type to use is 'AT_REST_PATH'. Here is that file on GitHub (right near the top of the file):
https://github.com/moqui/mantle-usl/blob/master/data/MantleSetupData.xml
The best documentation for most things to do with REST requests in Moqui, is currently in the comments in the 'rest.xml' file that actually processes the incoming requests (ie handles the /rest path). You can see this on GitHub here:
https://github.com/moqui/moqui-runtime/blob/master/base-component/webroot/screen/webroot/rest.xml

Calling uber API

When I call ubers API from my front end, the call gets blocked with the following error: No 'Access-Control-Allow-Origin' header is present on the requested resource. However, when I call from a node js application the call goes through just fine. The code is the exact same. See below:
$.ajax({
url: "https://api.uber.com/v1/estimates/price",
headers: {
Authorization: "Token " + uberServerToken
},
success: function(result) {
};
This is due to CORS policy enforced by the browser. For cross domain requests the server must include a header Access-Control-Allow-Origin: *. This is likely on purpose as you should never include a server tonken in your client code. For the client you should be using a bearer token. Take a look at the Uber API documentation.
Since the server is at your own control you're free to make API requests to anywhere.