简体   繁体   中英

Enabling CORS on Azure Active Directory

I am trying to get a access token from Azure Active Directory programmatically using the following method in an Angular 6 application.

    let body1 = new FormData()
    body1.append("resource", environment.config.clientId)
    body1.append("grant_type", "client_credentials")
    body1.append("client_id", environment.config.clientId)
    body1.append("client_secret", "*****")

    return this._http.post("https://login.microsoftonline.com/" + environment.config.tenant + "/oauth2/token", body1)

I was able to retrieve an access token through this url in Postman but am blocked by CORS when calling it through my application. Error is below.

    Failed to load https://login.microsoftonline.com/*****/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:4200' is therefore not allowed access.

So, how do I enabled CORS on the Azure Active Directory for all domains?

Simple, you do not.

What you are doing is exposing your app's client secret to the public. Remember that the request will be made from the user's device . So they can observe it and capture your secret. This is why the token endpoint does not support CORS, and probably never will.

UPDATE: The token endpoint does now support CORS, if you configure a reply URL with the SPA platform. This allows usage of Authorization Code flow with PKCE. MSAL.js 2.0 supports this flow. Note this still does not involve a client secret.

The way to acquire tokens from a front-end JS app is to use Implicit Grant Flow or Authorization Code flow with PKCE. Or if you do need an app-only token, then you must do the request you tried from a back-end application.

Implicit grant flow allows you to get tokens directly from the authorization endpoint as the user signs in. You can use ADAL.JS/MSAL.JS to assist in this. You cannot have tokens without a user identity as your native app cannot prove its identity.

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