Miccrosoft Graph访问令牌无法获取(Javascript)

时间:2017-10-23 09:22:34

标签: oauth-2.0 azure-active-directory microsoft-graph

我正在为Office365编写一个应用程序,我需要获取用户的访问令牌,但一切似乎都很好,但是......:我的代码抛出了一个错误,但我的网络调试器显示它有一个很好的响应。 .. 我不明白为什么我会收到错误,即使回复没问题。

代码

async getUserAccesToken(code) {
    var resource = `https://login.microsoftonline.com/${tenantDomain}/oauth2/v2.0/token`;
    var tokenRequest = {
        client_id: clientId,
        scope: 'offline_access user.read',
        code: code,
        redirect_uri: 'http://localhost:3000/acces',
        grant_type: 'authorization_code',
        client_secret: clientSecreta
    }

    return await this.getEncodedPostResponse(resource, tokenRequest);
}

async getEncodedPostResponse(resource, postBody) {
    var encodedPostBody = Object.keys(postBody).map((key) => encodeURIComponent(key) + '=' + encodeURIComponent(postBody[key])).join('&');
    debugger;
    return await fetch(resource, {
            method: "POST",
            body: encodedPostBody,
            headers: new Headers({
                'Accept': 'application/json; charset=utf-8;',
                'Content-Type': 'application/x-www-form-urlencoded'
            })
        })
        .catch(err => {
            debugger;
        })
        .then(response => response.json())
        .then(jsonResponse => jsonResponse);
}

错误(1/2) ErrorDetails

错误(2/2) enter image description here

我的Chrome调试器中的成功回复 enter image description here

1 个答案:

答案 0 :(得分:1)

有几件事:

  • 您正在获得Access-Control-Allow-Origin。您的服务器需要在其HTTP响应的标头中定义跨域调用的规则。 Mozilla文档包含有关此主题的优秀文章:Cross-Origin Resource Sharing (CORS)

  • 您将访问令牌与授权码混淆。您getUserAccesToken实际上正在请求验证码。通过向端点发回POST以将您的Auth代码转换为访问令牌来返回访问令牌。

  • 您似乎正在尝试从客户端POST。此呼叫属于服务器端。您的第一个电话会按login.microsoftonline.com请求验证码。用户进行身份验证后,microsoftonline.com会将用户发送到redirect_uri。当您的服务器收到此请求时,它需要发出POST以获取该用户的访问令牌。

我有一篇文章介绍了授权代码流如何与您可能会发现有用的v2端点一起使用:Microsoft v2 Endpoint Primer