简体   繁体   English

在 Azure Active Directory 上启用 CORS

[英]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.我正在尝试在 Angular 6 应用程序中使用以下方法以编程方式从 Azure Active Directory 获取访问令牌。

    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.我能够通过 Postman 中的这个 url 检索访问令牌,但在通过我的应用程序调用它时被 CORS 阻止。 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?那么,如何在 Azure Active Directory 上为所有域启用 CORS?

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.这就是令牌端点不支持 CORS 并且可能永远不会支持的原因。

UPDATE: The token endpoint does now support CORS, if you configure a reply URL with the SPA platform.更新:令牌端点现在支持 CORS,如果您使用 SPA 平台配置回复 URL。 This allows usage of Authorization Code flow with PKCE.这允许将授权代码流与 PKCE 一起使用。 MSAL.js 2.0 supports this flow. MSAL.js 2.0 支持此流程。 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.从前端 JS 应用程序获取令牌的方法是使用带有 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.隐式授权流允许您在用户登录时直接从授权端点获取令牌。您可以使用 ADAL.JS/MSAL.JS 来协助完成此操作。 You cannot have tokens without a user identity as your native app cannot prove its identity.您不能拥有没有用户身份的令牌,因为您的本机应用程序无法证明其身份。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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