如何在PHP版Microsoft Graph SDK中获取并设置authCode参数
获取Microsoft Graph授权码($authCode)的完整流程
要拿到$authCode,你得走完OAuth2授权码流程的完整链路,分两步操作:生成授权跳转链接、处理回调接收授权码,具体实现如下:
1. 生成授权跳转URL
首先需要引导用户跳转到Microsoft的授权页面,让用户登录并授权你的应用访问日历数据。跳转URL必须包含以下核心参数:
client_id: 你的应用注册IDredirect_uri: 与Azure门户配置完全一致的回调地址(包括协议、域名、路径)response_type: 固定为code(表示请求授权码)scope: 需申请的权限,比如User.Read Calendars.Read(仅User.Read不足以获取日历数据)state: 随机字符串,用于防范CSRF攻击response_mode: 固定为query
PHP代码示例:
<?php $clientId = 'xxxxxxx'; $tenantId = 'xxxxxxx'; $redirectUri = 'https://www.example.org/oauth/'; $scopes = urlencode('User.Read Calendars.Read'); $state = bin2hex(random_bytes(16)); // 生成随机state值 // 存储state到session,后续回调时验证 session_start(); $_SESSION['oauth_state'] = $state; // 构造授权URL $authUrl = "https://login.microsoftonline.com/{$tenantId}/oauth2/v2.0/authorize?" . http_build_query([ 'client_id' => $clientId, 'redirect_uri' => $redirectUri, 'response_type' => 'code', 'scope' => $scopes, 'state' => $state, 'response_mode' => 'query' ]); // 跳转至授权页面 header("Location: {$authUrl}"); exit; ?>
2. 处理回调获取$authCode
用户完成授权后,Microsoft会自动跳转到你配置的redirect_uri,此时URL的查询参数中会携带code(即你需要的$authCode)和state。你需要在回调页面中获取该code,并验证state的有效性:
<?php session_start(); // 验证state,防止CSRF攻击 if (!isset($_GET['state']) || $_GET['state'] !== $_SESSION['oauth_state']) { die("Invalid state parameter"); } // 获取授权码 if (isset($_GET['code'])) { $authCode = $_GET['code']; // 将$authCode传入AuthorizationCodeContext继续后续流程 use Microsoft\Graph\GraphServiceClient; use Microsoft\Kiota\Abstractions\ApiException; use Microsoft\Kiota\Authentication\Oauth\AuthorizationCodeContext; $clientId = 'xxxxxxx'; $tenantId = 'xxxxxxx'; $clientSecret = 'xxxxx'; $redirectUri = 'https://www.example.org/oauth/'; $tokenRequestContext = new AuthorizationCodeContext( $tenantId, $clientId, $clientSecret, $authCode, $redirectUri ); $scopes = ['User.Read', 'Calendars.Read']; // 必须包含日历权限 $graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes); // 调用API获取日历数据示例 try { $calendars = $graphServiceClient->me()->calendars()->get()->wait(); foreach ($calendars as $calendar) { echo $calendar->getDisplayName() . "<br>"; } } catch (ApiException $e) { echo "Error: " . $e->getMessage(); } } else { // 用户拒绝授权的处理逻辑 die("Authorization failed: " . ($_GET['error_description'] ?? 'Unknown error')); } ?>
关键注意事项
- 回调地址严格匹配:Azure门户中配置的
redirect_uri和代码中的必须完全一致,不能出现协议(http/https)、路径的差异。 - 权限配置到位:要获取日历数据,必须申请
Calendars.Read或Calendars.ReadWrite权限,组织内应用还需要管理员授予同意。 - 授权码一次性使用:
$authCode只能用来换取一次access token,失效后需用refresh token重新获取。
内容的提问来源于stack exchange,提问作者Mattia Trombon
相关产品推荐
相关产品推荐

