Azure AD预检请求未返回数据

时间:2017-11-08 16:49:31

标签: javascript azure http http-headers azure-active-directory

我目前正在尝试向https://login.microsoftonline.com/XXX/oauth2/token端点发送帖子请求,以检索应用程序的访问令牌和刷新令牌。使用axios将发布请求发送到端点时,会发送预检,但不会返回任何响应。

错误:

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:3000' is therefore not allowed access.

然而,对axios post请求使用不同的方法,它返回数据但没有预检,并给出了不同的错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:3000' is therefore not allowed access.

两个Axios请求:

const data = new FormData();

 data.append('grant_type', this.config.grant_type); 
 data.append('client_id', this.config.client_id);
 data.append('code', localStorage.getItem('auth_code'));
 data.append('redirect_uri', this.config.redirect_uri);
 data.append('client_secret', this.config.client_secret);
 data.append('resource', this.config.client_id);

axios.post(`https://login.microsoftonline.com/${this.config.tenant}/oauth2/token`, data);

方法2:

  axios({
  method: 'post',
  contentType: 'application/json',
  url: `https://login.microsoftonline.com/${this.config.tenant}/oauth2/token`,
  data: {
    grant_type: this.config.grant_type,
    client_id: this.config.client_id,
    code: localStorage.getItem('auth_code'),
    redirect_uri: this.config.redirect_uri,
    client_secret: this.config.client_secret,
    resource: this.config.client_id
  }
});

这是axios请求本身或端点的问题吗?

1 个答案:

答案 0 :(得分:1)

您应该使用隐式授权流来获取访问令牌。您不能使用包含来自前端JavaScript的客户端密钥的流程!

  

您的客户密码(AKA您的应用密码)目前公开给访问您网站的任何人!

无法在前端JavaScript中使用客户端密钥。

您需要在应用的清单中启用隐式流,然后在您的应用中使用以下网址重定向到Azure AD:

https://login.microsoftonline.com/tenant-id-here/oauth2/authorize?client_id=your-client-id&response_type=id_token+token&resource=resource-id-for-api&redirect_uri=your-app-redirect-url

文档:https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-authentication-scenarios#single-page-application-spa