Reputation: 118
I have a React + Express app for which I am using the passport-azure-ad
OIDCStrategy, but I'm having trouble with CORS.
The error I am receiving is:
Access to XMLHttpRequest at 'https://login.microsoftonline.com/...' (redirected from '{SERVER_URL}') from origin '{FRONTEND_URL}' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My frontend and backend are on different domains (I added a header on the backend to allow the frontend origin). I tried adding both urls as Redirect URIs, but that doesn't seem to help.
Is there a way to set Access-Control-Allow-Origin headers in Azure? Or is there a configuration in the React code which I'm missing?
Upvotes: 0
Views: 745
Reputation: 1
You have to use CORS package in the backend and give CORS access in your domain like
const cors = require('cors')
var corsOptions = {
origin: '*',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(cors(corsOptions));
Upvotes: 0
Reputation: 415
I want to assume you already set up CORS options in your backend. So, from the error one could see that the frontend is able to access the backend but not able to get access to the 3 party 0auth from Microsoft azure right. I am sure if you ran both the frontend and backend on the same port it would be successful provided you already set up your azure account to receive requests from your backend end point.
The problem is you running it on different ports, your react app on a particular port and the backend on another port. Then you used fetch in the react app to try and get the backend which will then send requests using the passport-azure to Microsoft.
So instead of using fetch from react to backend to 0auth service, use an anchor tag.
Kindly check out this github issue as this person also encountered this same error
"Fixed. Don't use fetch from react to api to oauth service. Use a link (anchor/location.href) instead and let the flow of the oauth process take over in the browser." - what the issue owner said.
I hope it helps.
Upvotes: -1
Reputation: 689
Is there a way to set Access-Control-Allow-Origin headers in Azure? Or is there a configuration in the React code which I'm missing?
Generally, this error occurs when the front end and backend is running on different ports.
The browser will not accept the responses from the backend because of the CORS headers not present.
So, we have to add the CORS headers in the backend request to overcome this issue by using the cors npm
package below:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
It enables CORS headers with all the requests.
you can refer to cors documentation for more information.
Also, We can enable CORS for Azure App Service in azure portal as mentioned here.
Upvotes: 1