使用PHP从Microsoft Graph API获取访问令牌

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

我想将outlook 365日历事件与我的系统同步。我的系统是后台服务,而不是应用程序,因此我无法为用户提供登录屏幕以批准授权。

我关注此链接以获取访问令牌(无需用户访问):https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_service

我通过浏览器调用此链接(手动粘贴),以便批准管理员权限,获得批准筛选和批准的管理员权限:https://login.microsoftonline.com/mycompany.onmicrosoft.com/adminconsent?client_id=xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx&state=12345&redirect_uri=https%3A%2F%2Fmyserver.mycompany.com%2Fsugarcrmmaintest%2Fresponse.php

响应网址按计划调用,我收到了回复。

现在我想获得访问令牌。根据手册,我一直在调用这段代码,但没有任何反应,我也没有得到回复:

$ clientId =“xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx”; $ clientSecret =“mysecret”; $ responseUri =“https%3A%2F%2Fmyserver.mycompany.com%2Fsugarcrmmaintest%2Fresponse.php”;

        $postUrl = "/mycomp.onmicrosoft.com/oauth2/v2.0/token";
    $hostname = "login.microsoftonline.com";
        $fullurl = "https://login.microsoftonline.com/mycompany.onmicrosoft.com/token";

        $headers = array(
            "POST " . $postUrl . " HTTP/1.1",
            "Host: " . $hostname,
            "Content-type: application/x-www-form-urlencoded",
        );

    $post_params = array(
        "client_id" => $clientId,                    
        "scope" => "https%3A%2F%2Fgraph.microsoft.com%2F.default",
        "client_secret" => $clientSecret,
        "grant_type" => "client_credentials",
        );

    $curl = curl_init($fullurl);

        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_params);
        curl_setopt($curl, CURLOPT_HTTPHEADER, Array("application/x-www-form-urlencoded"));
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $response = curl_exec($curl);

我忘记了什么吗?

这是培训页面中的解释:

enter image description here在这里阅读了数十篇文章,但所有这些都是涉及授权屏幕的例子,我无法提供。我需要同步作为后台服务。

php azure-active-directory microsoft-graph
2个回答
1
投票
  1. 我会仔细检查您通过cURL发送的URL。我会尝试用https://login.microsoftonline.com/mycompany.onmicrosoft.com/oauth2/v2.0/token测试它。当你两次调用CURLOPT_HEADER时,你可能会在标题中覆盖它。
  2. 如果您在开发环境中工作,请尝试设置curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

0
投票

有很多方法可以实现这一目标。以下示例使用Microsoft Graph SDK for PHP

适用于PHP的Microsoft Graph SDK不包含任何默认的身份验证实现。 thenetworg/oauth2-azure library将为您处理标准Oauth2,并提供可用于查询图表的令牌。

要作为应用程序进行身份验证,您可以使用预先安装此库的Guzzle HTTP client,例如:

$guzzle = new \GuzzleHttp\Client();
$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/v2.0/token';
$token = json_decode($guzzle->post($url, [
    'form_params' => [
        'client_id' => $clientId,
        'client_secret' => $clientSecret,
        'scope' => 'https://graph.microsoft.com/.default',
        'grant_type' => 'client_credentials',
    ],
])->getBody()->getContents());
$accessToken = $token->access_token;

您还可以使用thephpleague/oauth2-client对用户进行身份验证并获取访问令牌。

Here是授权代码授权流程示例的一个示例。但是您也可以使用use client_credentials flow

请告诉我它是否有帮助!

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