To integrate Microsoft Graph 2.0 with Laravel 12, you can follow these steps. This example assumes you want to authenticate users via Microsoft and access their data using Microsoft Graph.
Step 1: Install Required Packages
First, ensure you have the necessary packages installed. You can use the microsoft/microsoft-graph package for interacting with Microsoft Graph and league/oauth2-client for OAuth2 authentication.
composer require microsoft/microsoft-graph
composer require league/oauth2-client
Step 2: Set Up Environment Variables
Add the necessary Microsoft Graph credentials to your .env file:
MICROSOFT_CLIENT_ID=your-client-id
MICROSOFT_CLIENT_SECRET=your-client-secret
MICROSOFT_REDIRECT_URI=https://your-app-url.com/callback
Step 3: Create an OAuth2 Provider
Create a custom OAuth2 provider for Microsoft. You can place this in app/Providers/MicrosoftProvider.php.
<?php
namespace App\Providers;
use League\OAuth2\Client\Provider\AbstractProvider;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use Psr\Http\Message\ResponseInterface;
class MicrosoftProvider extends AbstractProvider
{
protected function getBaseAuthorizationUrl()
{
return 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize';
}
protected function getBaseAccessTokenUrl(array $params)
{
return 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
}
protected function getResourceOwnerDetailsUrl(AccessToken $token)
{
return 'https://graph.microsoft.com/v1.0/me';
}
protected function getDefaultScopes()
{
return ['openid', 'profile', 'email', 'offline_access', 'User.Read'];
}
protected function checkResponse(ResponseInterface $response, $data)
{
if (isset($data['error'])) {
throw new IdentityProviderException(
$data['error_description'] ?? $data['message'],
$response->getStatusCode(),
$response
);
}
}
protected function createResourceOwner(array $response, AccessToken $token)
{
return new MicrosoftResourceOwner($response);
}
}
Step 4: Implement Authentication Logic
Create routes and controllers to handle the authentication flow.
In routes/web.php:
use App\Providers\MicrosoftProvider;
use Illuminate\Support\Facades\Route;
Route::get('/login', function () {
$provider = new MicrosoftProvider([
'clientId' => env('MICROSOFT_CLIENT_ID'),
'clientSecret' => env('MICROSOFT_CLIENT_SECRET'),
'redirectUri' => env('MICROSOFT_REDIRECT_URI'),
]);
$authorizationUrl = $provider->getAuthorizationUrl();
session(['oauth2state' => $provider->getState()]);
return redirect($authorizationUrl);
});
Route::get('/callback', function () {
$provider = new MicrosoftProvider([
'clientId' => env('MICROSOFT_CLIENT_ID'),
'clientSecret' => env('MICROSOFT_CLIENT_SECRET'),
'redirectUri' => env('MICROSOFT_REDIRECT_URI'),
]);
if (request('state') !== session('oauth2state')) {
session()->forget('oauth2state');
exit('Invalid state');
}
try {
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => request('code')
]);
$resourceOwner = $provider->getResourceOwner($accessToken);
$user = $resourceOwner->toArray();
// Use $user data as needed
dd($user);
} catch (\Exception $e) {
exit('Failed to get access token: ' . $e->getMessage());
}
});
Step 5: Access Microsoft Graph
Once authenticated, you can use the microsoft/microsoft-graph package to interact with Microsoft Graph.
use Microsoft\Graph\Graph;
use Microsoft\Graph\Model;
$graph = new Graph();
$graph->setAccessToken($accessToken->getToken());
$user = $graph->createRequest("GET", "/me")
->setReturnType(Model\User::class)
->execute();
dd($user);
This setup will allow you to authenticate users with Microsoft and access their data using Microsoft Graph in a Laravel 12 application. Adjust the scopes and endpoints as needed for your specific use case.