How to res.redirect to oauth url with express - node.js

I got a big problem with express.js and react. I’m trying to make google authentication via oauth2 library but I can’t get the main page redirect to auth URL from server-side. Can anyone help me out??
I've tried to send URL variable to the client but I failed, I used open (npm package) but it can't be used on lab machines where my code is.
aurl = (oAuth.generateAuthUrl({
access_type: "offline",
scope: SCOPES,
state: JSON.stringify({filename: req.file.originalname, title, description, category, audience, purpose, playlist}) }));
desc = req.body.geoloc+":"+req.body.purpose+":"+req.body.title+":"+"language"+":"+req.body.content+":"+req.body.audience+":"+req.body.detail;
res.redirect(aurl);
Then in Chrome, I get these errors:
"GET https://accounts.google.com/o/oauth2/auth?access_type=offline...
400" and "Access to XMLHttpRequest at
'https://accounts.google.com/o/oauth2/auth?access_type=offline...'
(redirected from 'http://localhost:8000/upload') from origin 'null'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin'
header is present on the requested resource.strong text

Related

Unable to make an API request to Twitter for .json return duo to CORS - Chrome extension- Manifest 3

I am trying to build a basic Chrome that shows an HTML page that I built on chrome://newtab. (Manifest 3).
Flow: My HTML file calls a local script file. The script file has a fetch function. The function calls the twitter 2.0 API with GET and a bearer auth to fetch all of the tweets made by a specific account. Account is recognized by id from twitter.
Results from the console:
"Access to fetch at 'https://api.twitter.com/2/users/44196397/tweets' from origin 'chrome-extension://epfgicoboagicldadiiggnmfgholpmna' 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."
The code I use:
fetch("https://api.twitter.com/2/users/44196397/tweets", {method: 'GET', headers : {Authorization : "Bearer ..🤫.."}}) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error));
Manifest includes: version:3, name, version, decription, author, chrome_url_overrides {newtab: index.html}, permissions [storage].
Tried:
no-cors header in fetch() - getting 401 error (according to Google, not supported on the blue side)
Postman - worked
curl commend on my PC - worked
Placing the script on an external server (I thought there is some sort of a security blockade for extensions, so then I could just extract the text) - CORS error also there. (On 000webhosting, no access to server config).
So from here on out, I'm stuck.I will highly appreciate any feedback!
Note: I'm new. Please ELI5, started programming with ChatGPT. Sorry if the post is overdetailed, didn't want to overlook something which might be important.
Cheers!

Google maps API returning No 'Access-Control-Allow-Origin' with Node.js module

I am using the node module #googlemaps/google-maps-services-js to make requests to the Google maps API. When I make requests to any of their API endpoints (e.g directions API, places API, etc), I get these errors:
xhr.js:125 Refused to set unsafe header "User-Agent"
xhr.js:125 Refused to set unsafe header "Accept-Encoding"
localhost/:1 Access to XMLHttpRequest at 'https://maps.googleapis.com/maps/api/directions/json?
destination=Universal%20Studios%20Hollywood&key=mykey&origin=Disneyland' from
origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header
is present on the requested resource.
Here are the things I've tried:
1. I've tried accessing different API endpoints, (e.g instead of directions, places.)
2. I've tried adding headers manually, but I don't really know what headers i should add to make this work.
3. I have also tried accessing this API from my normal browser (Google). It returned a proper response, so it isn't an improper API key.
Also Note:
I have activated my API key, activated each of the APIs I want to use, and I have set up a billing account with Google Cloud Platform.
Not for browser
#googlemaps/google-maps-services-js is not compatible with browser environments because the Google server DOES NOT return the necessary CORS headers. This package is for Nodejs.
From the readme:
Alternative [Preferred]
Use https://developers.google.com/maps/documentation/javascript/overview.
Your code will look similar to the following:
const directionsService = new google.maps.DirectionsService();
const request = {
origin: 'Disneyland',
destination: 'Universal Studios Hollywood',
travelMode: 'DRIVING'
};
const response = await directionsService.route(request);
A directions tutorial is available.
Alternative 2
Proxy the directions endpoint through your own server and add CORS headers.
are you using cors on your endpoint?
you should allow your endpoint to respond to a different origin (this is why is Cross Origin, because it is different from the location of your endpoint).
here you can find a good/simple example of using cors policy in nodejs

Express.js: CORS policy blocking Stripe API request

I am trying to send form data from React/Redux to a locally hosted Express.js server. However, I am getting CORS errors:
Access to XMLHttpRequest at 'http://localhost:4000/api/donate' 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.
VM6535:1 Cross-Origin Read Blocking (CORB) blocked cross-origin
response http://localhost:4000/api/donate with MIME type text/html. See
https://www.chromestatus.com/feature/5629709824032768 for more details.
createError.js:17 Uncaught (in promise) Error: Network Error
at createError (createError.js:17)
at XMLHttpRequest.handleError (xhr.js:87)
This was the initial CORS policy I set to have Express.js receive my React Data:
// index.js in the backend project
let cors = require("cors");
const corsOptions = {origin : "http://localhost:3000/" }; // React app is on port 3000
router.post('/api/donate', cors(corsOptions), (req, res, next) => { ....
I was sending test credit card charges to Stripe using string data before and it worked with no errors. Only difference now is that before I was only sending data using form/input components from react-stripe-elements whereas now I also send some data from my Redux store.
Even now with this error, Stripe still responds with partial token data (maybe default values, not sure).
Is something missing with my CORS policy? I thought whitelisting localhost:3000 would have fixed it, and it appeared to. But it is still issuing the error above.
CORB is a new policy enforced by certain browsers. It enforces the idea of did I get back what I requested. so if you make a response with JSON headers and you get back text/html like you did in this case then chrome will eat the response and throw the second error you see. change your content headers to text/html and it will probably work for you.

Is there anything I can do on the front end to read the response of a POST request to another domain?

I have a form
render() {
return (
<form onSubmit={this.handleSubmit}>
...
</form>
);
}
On submit I make a post request and print the response
handleSubmit(event) {
axios.post('https://.../oauth2/token', {
firstName: this.state.username,
password: this.state.password,
grant_type: password
})
.then(response => console.log(response))
event.preventDefault();
}
The printed response is
Failed to load https://.../oauth2/token: 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:3000' is therefore not allowed
access. The response had HTTP status code 400.
I understand that this is supposed to protect against cookie abuse. But is there anything I can do on the front end to get the response? Maybe I can state in the request that I don't want to use any cookie rights.
No 'Access-Control-Allow-Origin' header is present on the requested resource
Right there tells me what's wrong. You've got a problem with CORS (Cross-Origin Resource Sharing). If you're using Chrome, you can use an extension for it.
For a permanent solution, you'll have to enable CORS on your host server. I can't offer much help with that, as I've got no idea what your backend looks like. You can try searching for " CORS". Personally, I just use the extension when I'm developing for simplicity's sake, but I'm only working on an AngularJS mobile app.

Google OAuth2: Redirect has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect

Trying to implement Google OAuth2 and using https://github.com/google/google-api-nodejs-client#authorizing-and-authenticating as reference. When redirecting user to consent page like this
var url = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: some_scope
});
res.redirect(url);
I get this error in browser console (links edited):
XMLHttpRequest cannot load localhost:8080/myPageName. Redirect from localhost:8080/myPageName to accounts.google.com/o/oauth2/auth?access_type=... has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.
The strange thing is that I am getting this error only when executing the flow from GUI (user presses the button; angular2 front-end). When I put localhost:8080/myPageName directly into the browser address bar everything works fine (get consent form and then tokens).
Any help is appreciated. Thank you.
I had the same issue (with a react frontend, but it's the same).
This is probably because from the server you use redirect, which triggers CORS (even if from your server you allow it).
you have to return the redirect URL to your front-end in some other way, capture it from the front-end app and then call the URL you need to invoke.
A simple solution is create a hidden link with the required query parameters and click the link using JavaScript, if google supports HTTP POST submission then a hidden form can be created and submitted directly again using JavaScript magic to bypass the CORS restriction which I guess is either already removed or will be removed in near future.

Resources