简体   繁体   中英

Access to XMLHttpRequest at 'https://login.microsoftonline.com/xxx from origin 'http://localhost:4200' has been blocked by CORS policy

Seems like a repeated question yet couldn't resolve it. I have angular 6 app that uses Msal to force users to login. After successful login, I am making a request to aad's token end point passing service principal credentials (application's app id and client secret) to get access token to access graph api as mentioned here . This is where I am getting CORS policy error.

When I disable chrome browser security, I am not getting any CORS error and able to get access token.

Why am I getting CORS error only when I try to get access token using service principal credentials and not on user's login using msal?

Do I need to have any script at browser end to make it work?

how do I achieve it without compromising security?

The login authority is : https://login.microsoftonline.com/ {tenant id}/

The token endpoint for service principal is: https://login.microsoftonline.com/ {tenant id}/oauth2/v2.0/token

Usually traditional or regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. So the browser is blocking it as it usually allows a request in the same origin for security reasons. Though Postman can handle this kind of request because they are not restricted by this policy.

To integrate Azure Active Directory in javascript, Its recomended to use azure-active-directory-library-for-js which is a library in javascript for frontend to integrate azure active directory with a ease, by using implicit grant flow ,It also has the advantage of eliminating any requirements for cross origin calls, which are necessary if the JavaScript application is required to contact the token endpoint. You also can have a look Here is a thread which discuss same topic and show more about how to use MSAL.JS , please refer to that .

You can also see the client side request pattern in java script here . I believe above mentioned process may help you.

For More details you can read this:

MSAL Single page application

Implementation of ADAL

Single page application using MSAL for B2C

Thank you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM