Skip to content

Instantly share code, notes, and snippets.

@PetrovStark
Last active December 20, 2023 18:11
Show Gist options
  • Save PetrovStark/b8846a592e5c30612d48b4bb9fec2084 to your computer and use it in GitHub Desktop.
Save PetrovStark/b8846a592e5c30612d48b4bb9fec2084 to your computer and use it in GitHub Desktop.
Two ways to login with AAD, one using cURL, another using GuzzleHttp. For the guzzle method, there's a composer.json file indexed.
<?php
$tenantId = 'common';
$authenticationUrl = "https://login.microsoft.com/{$tenantId}/oauth2/v2.0/authorize";
$clientId = "{seu-client-id}";
$clientSecret = '{seu-client-secret}';
$redirectUri = '{seu-redirect-uri}';
$scope = "openid profile offline_access User.Read"; // Escopo de permissões necessárias
$authenticationUrl .= "?client_id=$clientId&redirect_uri=$redirectUri&response_type=code&scope=$scope";
if (isset($_GET['code'])) {
try {
$tokenUrl = "https://login.microsoft.com/$tenantId/oauth2/v2.0/token";
$postData = [
'grant_type' => 'authorization_code',
'redirect_uri' => $redirectUri,
'client_id' => $clientId,
'client_secret' => $clientSecret,
'code' => $_GET['code']
];
// Inicializa cURL session
$ch = curl_init($tokenUrl);
// Configura opções cURL
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Executa a requisição cURL
$response = curl_exec($ch);
// Verifica por erros na requisição cURL
if ($response === false) {
throw new Exception('Erro na requisição cURL: ' . curl_error($ch));
}
// Fecha a sessão cURL
curl_close($ch);
$tokenData = json_decode($response, true);
$accessToken = $tokenData['access_token'];
$graphApiUrl = "https://graph.microsoft.com/v1.0/me";
// Inicializa uma nova sessão cURL para a segunda requisição
$ch = curl_init($graphApiUrl);
// Configura opções cURL para a segunda requisição
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $accessToken]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Executa a segunda requisição cURL
$response = curl_exec($ch);
// Verifica por erros na segunda requisição cURL
if ($response === false) {
throw new Exception('Erro na segunda requisição cURL: ' . curl_error($ch));
}
// Fecha a segunda sessão cURL
curl_close($ch);
$userData = json_decode($response, true);
$objectId = $userData['id'];
echo "Object ID: $objectId";
echo "<pre>";
print_r(json_encode($userData));
echo "</pre>";
} catch (Exception $e) {
header("Location: {$authenticationUrl}");
exit();
}
} else {
header("Location: {$authenticationUrl}");
exit();
}
?>
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$tenantId = 'common';
$authenticationUrl = "https://login.microsoft.com/{$tenantId}/oauth2/v2.0/authorize";
$clientId = "{seu-client-id}";
$clientSecret = '{seu-client-secret}';
$redirectUri = '{seu-redirect-uri}';
$scope = "openid profile offline_access User.Read"; // Escopo de permissões necessárias
$authenticationUrl .= "?client_id=$clientId&redirect_uri=$redirectUri&response_type=code&scope=$scope";
if (isset($_GET['code'])) {
try {
$tokenUrl = "https://login.microsoft.com/$tenantId/oauth2/v2.0/token";
$client = new Client();
$response = $client->post($tokenUrl, [
'form_params' => [
'grant_type' => 'authorization_code',
'redirect_uri' => $redirectUri,
'client_id' => $clientId,
'client_secret' => $clientSecret,
'code' => $_GET['code']
]
]);
$tokenData = json_decode($response->getBody(), true);
$accessToken = $tokenData['access_token'];
$graphApiUrl = "https://graph.microsoft.com/v1.0/me";
$response = $client->get($graphApiUrl, [
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
]
]);
$userData = json_decode($response->getBody(), true);
$objectId = $userData['id'];
echo "Object ID: $objectId";
echo "<pre>";
print_r(json_encode($userData));
echo "</pre>";
} catch (Exception $e) {
header("Location: {$authenticationUrl}");
exit();
}
} else {
header("Location: {$authenticationUrl}");
exit();
}
{
"require": {
"guzzlehttp/guzzle": "^7.8"
},
"config": {
"allow-plugins": {
"php-http/discovery": true
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment