Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
910 views
in Technique[技术] by (71.8m points)

angular - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...