从Nodejs代码生成Microsoft Graph API令牌

时间:2019-12-17 07:14:59

标签: node.js microsoft-graph

我想访问Microsoft Graph API,为此,我尝试从Nodejs代码生成令牌。我从nodejs获取令牌,但是当我在jwt.io中解码此令牌时。我没有看到范围参数。另外,当我在访问Microsoft Graph API时使用此令牌时,也会出现错误

  

Authorization_RequestDenied

代码生成屏幕截图

enter image description here

1 个答案:

答案 0 :(得分:0)

文档https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow清楚地说,如果

grant_type: "client_credentials"响应如下,won't have scope variable

{
  "token_type": "Bearer",
  "expires_in": 3599,
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBP..."
}

这就是您所得到的,因此可以正常工作。

您正在寻找scope变量,因此必须遵循

grant_type=authorization_code,响应为

{
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...",
    "token_type": "Bearer",
    "expires_in": 3599,
    "scope": "https%3A%2F%2Fgraph.microsoft.com%2Fuser.read",
    "refresh_token": "AwABAAAAvPM1KaPlrEqdFSBzjqfTGAMxZGUTdM0t4B4...",
    "id_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctOD...",
}

在这里您将获得scope变量,引用为https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow

因此,无论client Credential还是authorisation_code,您的通话方式都很重要

编辑

您必须按以下方式调用authorise API:

https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&response_mode=query
&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read
&state=12345

使用urlparams修改您的请求,您将获得如下响应:

GET https://login.microsoftonline.com/common/oauth2/nativeclient?
code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrq...
&state=12345

这是您要查找的代码。因此,在此之后,您必须进行上述令牌调用。