How to fix CORS Errors in Angular when calling Graph API (SendMail Purpose)

Fabian_Haering 81 Reputation points
2024-05-26T09:36:40.73+00:00

Hi all.

I'm quite new to development in angular and I'm currently facing an issue with retrieving the bearer token from the graph endpoint. I've already set up an app registration in my tenant to provide my application with the necessary permissions (SendMail using application permissions to ensure no user interaction is required). Everything works fine with Postman or Powershell. But when I try to get the access token using my angular authentication service, I always get a CORS error. My angular application is SPA based and there should be no login before. So I want to get the token using a normal https POST call and use the token to send the mail.

I've already tried to use an athentication library like msal-browser (not able to work with client credentials) or msal-node (several other errors I couldn't handle in my application) and tried to bypass the CORS error when setting up a proxy.conf.json file in my app. But nothing helps.

Basically, do I need to use an authentication library to get rid of the CORS error? Using Postman & PowerShell, it's just a simple POST call so that I get the token. And I thought that I can to the same for my angular app.

By the way my angular project is running on localhost port and this entry is done in my redirect URI in the app registration.

Best regards,
Fabian

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
11,446 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Deepanshu Sharma 490 Reputation points Microsoft Vendor
    2024-05-26T18:57:20.74+00:00

    Hi Fabian_Haering

    • The CORS (Cross-Origin Resource Sharing) error occurs because your Angular app is making a request to a different domain (the Microsoft Graph API) than the one where your app is hosted (localhost in your case).
    • Browsers enforce CORS policies to prevent unauthorized cross-origin requests.
    • When you use Postman or PowerShell, they don’t enforce CORS, which is why you don’t encounter the issue there.

    Solutions:

    • To resolve the CORS error, you have a few options:
      • Proxy Configuration:
        • Set up a proxy configuration in your Angular app to forward requests to the Microsoft Graph API.
        • This way, your Angular app sends requests to the same domain (localhost), and the proxy forwards them to the Graph API.
        • You can achieve this by creating a proxy.conf.json file in your Angular project and configuring it to point to the Graph API URL when running locally.