MS OAuth2.0 演示
"; if (isset ($_SESSION['msatg'])){ echo "已驗證".$_SESSION["uname"]." </h2><br> ”; echo '<p><a href="?action=logout">注銷</a></p>'; } //如果會話結束 else echo '
您可以登錄與 Microsoft</p></h2>'; if ($_GET['操作'] == '登錄'){ $params = array ('client_id' => $appid, 'redirect_uri' => 'https://xxx.co/projects/test.php', 'response_type' => '令牌', '范圍' => 'https://graph.microsoft.com/User.Read', '狀態(tài)' => $_SESSION['狀態(tài)']); header('位置:'.$login_url.'?'.http_build_query($params)); } 回聲' <腳本> url = window.location.href; i=url.indexOf(“#”); 如果(我> 0){ url=url.replace("#","?"); window.location.href=url;} </腳本> '; if (array_key_exists ('access_token', $_GET)) { $_SESSION['t'] = $_GET['access_token']; $t = $_SESSION['t']; $ch=curl_init(); curl_setopt($ch, CURLOPT_HTTPHEADER, array('授權:承載'.$t, '內容類型:application/json')); curl_setopt($ch,CURLOPT_URL,“https://graph.microsoft.com/v1.0/me/”); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $rez = json_decode(curl_exec($ch), 1); if (array_key_exists ('錯誤', $rez)){ var_dump($rez['錯誤']); 死(); } 別的 { $_SESSION['msatg'] = 1; //授權并驗證 $_SESSION['uname'] = $rez['displayName']; $_SESSION['id'] = $rez['id']; } 卷曲關閉($ch); header('位置:https://xxxx.co/projects/test.php'); } if ($_GET['action'] == '注銷'){ 取消設置($_SESSION['msatg']); header('位置:https://xxxx.co/projects/test.php'); }</pre> <p>當我們打開此代碼時,它會要求登錄。我們不希望這樣。將使用 php 直接提取電子郵件</p>
使用OAuth 2.0授權
對用戶進行身份驗證并獲取訪問令牌。并使用它調用 Microsoft Graph API
來檢索用戶的電子郵件。
對于您的問題,在您未登錄時可能會出現(xiàn)登錄頁面。要解決此問題,您需要使用 OAuth 2.0 客戶端憑據(jù)
而不是授權代碼。 p>
使用客戶端憑據(jù)獲取訪問令牌的示例代碼。
$tenantId = 'your-tenant-id'; $client_id = 'your-client-id'; $client_secret = 'your-client-secret'; $resource = 'https://graph.microsoft.com'; $tokenEndpoint = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token'; $data = array( 'grant_type' => 'client_credentials', 'client_id' => $client_id, 'client_secret' => $client_secret, 'resource' => $resource ); $options = array( 'http' => array( 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data) ) ); $context = stream_context_create($options); $result = file_get_contents($tokenEndpoint, false, $context); $token = json_decode($result)->access_token;
獲取訪問令牌后,您可以使用它來調用 Microsoft Graph API
并檢索用戶的電子郵件。
檢索用戶電子郵件的示例代碼。
php $graphApiEndpoint = 'https://graph.microsoft.com/v1.0/me/messages'; $options = array( 'http' => array( 'header' => "Authorization: Bearer $token\r\n" . "Content-type: application/json\r\n", 'method' => 'GET' ) ); $context = stream_context_create($options); $result = file_get_contents($graphApiEndpoint, false, $context); $messages = json_decode($result)->value;