Getting CORS error when using Passport Azure AD

580 views Asked by At

I have my Express API server as well as the SPA hosted on Heroku. The SPA uses Azure ad authentication using MSAL. The APIs are secured using Passport-azure-ad. Everything was working well in my localhost and the requests made where getting a success response. However on uploading the changes to Heroku I am now getting the CORS error. I have registered the API on Azure AD and exposed the API to my SPA. Any reason why I am still getting the error?

Access to fetch at 'https://myTestApp-server.herokuapp.com/getUsers' from origin 'https://myTestApp.herokuapp.com' 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.
1

There are 1 answers

0
Imran On

To avoid the CORS error, make sure to add the header like below:

  • While adding the Allowed origins use * to allow all like below:

enter image description here

  • Otherwise, add particular origins like below:

enter image description here

  • Make sure to restart the Api after making the above changes.
  • Check whether you are using correct version of NodeJs that matches the runtime you’re developing and testing.
  • Try modifying CORS policy by adding .SetIsOriginAllowed((host)=> true)"
  • If you are adding header via Nodejs code make use of below command:
res.setHeader('Access-Control-Allow-Origin', '*');

Or

res.setHeader('Access-Control-Allow-Origin',
https://myTestApp-server.herokuapp.com:4200');

For more in detail, please refer below link:

Azure App Service No ‘Access-Control-Allow-Origin’ header is present

No 'Access-Control-Allow-Origin' header is present on the requested resource in angular app

3 Ways to Fix the CORS Error and How the Access-Control-Allow-Origin Header Works