使用纯JavaScript获取Microsoft graph api的访问令牌

问题描述 投票:-1回答:1

我尝试使用ajax调用使用Microsoft graph api获取计划数据但是我得到https://graph.microsoft.com/v1.0/me/planner/tasks 400(错误请求):

function requestToken() {
        $.ajax({
            "async": true,
            "crossDomain": true,
            "url": "https://cors-anywhere.herokuapp.com/https://login.microsoftonline.com/common/oauth2/v2.0/token", // Pass your tenant name instead of sharepointtechie
            "method": "POST",
            "headers": {
                "content-type": "application/x-www-form-urlencoded"
            },
            "data": {
                "grant_type": "client_credentials",
                "client_id ": "--REDACTED--", //Provide your app id
                "client_secret": "--REDACTED--",

                                     //Provide your client secret genereated from your app
                "scope ": "https://graph.microsoft.com/.default"
            },
            success: function (response) {
                console.log(response);
                token = response.access_token;


                $.ajax({
                    url: 'https://graph.microsoft.com/v1.0/me/planner/tasks',
                    type: 'GET',
                    dataType: 'json',
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('Authorization', 'Bearer '+token+'');
                    },
                    data: {},
                    success: function (results) {                            
                        console.log(results);
                        debugger;
                    },
                    error: function (error) {
                        console.log("Error in getting data: " + error);
                    }
                });
            }

        })
    }

从planner寻找json数据,但是从图api获取时得到错误代码https://graph.microsoft.com/v1.0/me/planner/tasks 400(Bad Request)。

azure-active-directory sharepoint-2013 microsoft-graph
1个回答
0
投票

首先,您现在共享的代码存在几个主要问题:

  1. 您不应该使用客户端凭据授予,即clientId和客户端密钥从客户端JavaScript代码调用Microsoft Graph API,它仅适用于守护程序或服务等机密客户端。
  2. 无论如何你试图点击endpont https://graph.microsoft.com/v1.0/me/planner/tasks,其中包括仅对用户身份有效的关键字me。因此,您应该尝试使用当前登录用户的身份获取令牌,或者如果用户未登录则提示用户。

您可以使用Microsoft Graph JavaScript Client Library来调用Microsoft Graph。

客户端库的链接还提供了示例代码的良好分步指导。

注意:请不要将您的客户机密或任何其他敏感信息作为您在stackoverflow上的问题的一部分。我现在要编辑这个问题,但你仍然应该删除你的应用程序的这个特殊秘密,并为将来的使用生成新的秘密。

© www.soinside.com 2019 - 2024. All rights reserved.