-2

我有一个用例,我需要从 Outlook 中读取邮件,根据文档我需要进行 2 个 api 调用,如下所示

1 https://login.microsoftonline.com/common/oauth2/v2.0/authorize

2 https://login.microsoftonline.com/common/oauth2/v2.0/token

在第一次 api 调用中,我传递了所需的参数,例如 client_id、redirect_uri、response_type、scope

我可以在网络浏览器中的第一个 api 中获取访问代码,而在邮递员中我正在获取 html 代码

有没有办法以编程方式获取访问代码?

4

1 回答 1

0

听起来您想在没有用户的情况下获取访问权限,请参阅章节4. Get an access token

这是我的 Python 和 Node.js 示例代码及其结果,如下所示。

requests使用包的 Python 代码

import requests

tenant = "<your tenant id>"
url = f"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token"

client_id = "<your client id>"
client_secret = "<your client secret>"

body = {'client_id': client_id, 'scope': 'https://graph.microsoft.com/.default', 'client_secret': client_secret, 'grant_type': 'client_credentials'}

r = requests.post(url, data=body)

json_text = r.text

import json
j = json.loads(json_text)
print('The json object of /token response =>', j)
access_token = j['access_token']
print('access_token =>', access_token)

在此处输入图像描述

request使用包的 Node.js 代码

const request = require('request');
const querystring = require('querystring');

const tenant = '<your tenant id>';
var url = `https://login.microsoftonline.com/${tenant}/oauth2/v2.0/token`;

var client_id = "<your client id>";
var client_secret = "<your client secret>";

var body = querystring.stringify({'client_id': client_id, 'scope': 'https://graph.microsoft.com/.default', 'client_secret': client_secret, 'grant_type': 'client_credentials'});

request.post({
    headers: {'Content-Type' : 'application/x-www-form-urlencoded'},
    url:     url,
    body:    body
  }, function(error, response, body){
    console.log('The json object of /token response =>', body);
    var j = JSON.parse(body);
    console.log('access_token =>', j['access_token']);
  });

在此处输入图像描述

于 2019-11-15T09:23:29.337 回答