oAuth 2 — Get your Office 365 token in Laravel
With the following code sample you can retrieve an oAuth 2 token for your Microsoft account. This is specifically for the Credentials Grant authorization flow.
If you want to learn more about the available flows oAuth 2 has, I recommend this article by Athiththan Kathirgamasegaran.
Microsoft supports 3 flows, you can read more about them here.
$tennantId = '<tennant-id>';
$scope = 'https://ps.outlook.com/.default';
$redirectUrl = 'https://callbackurl';
$appId = '<app-id>';
$secretId = '<secret-id>';
$secret = '<secret>';
$url = "https://login.microsoftonline.com/{$tennantId}/oauth2/v2.0/token?scope={$scope}&client_id={$secretId}&redirect_uri={$redirectUrl}";
$config = [
'grant_type' => 'client_credentials',
'client_id' => $appId,
'client_secret' => $secret,
'scope' => $scope,
];
$response = \Illuminate\Support\Facades\Http::asForm()->post($url, $config);
$data = $response->json();
\Illuminate\Support\Facades\Log::info('server error: ' . $response->serverError());
\Illuminate\Support\Facades\Log::info('server error: ' . $response->body());
\Illuminate\Support\Facades\Log::info('server error: ' . $response->status());
$token = \Illuminate\Support\Arr::get($data, 'access_token');
$expiresOn = \Illuminate\Support\Arr::get($data, 'expires_on');
$tokenType = \Illuminate\Support\Arr::get($data, 'token_type');
$expiresIn = \Illuminate\Support\Arr::get($data, 'expires_in');
$expExpiresIn = \Illuminate\Support\Arr::get($data, 'ext_expires_in');
\Illuminate\Support\Facades\Log::info("Token: {$token}");
I this sample I use a scope for retrieving e-mails. Depending on the data you are working with you need a specific scope.
Microsoft can be a bit awkward concerning naming parameters and stuff. In this case you need to provide the app-id as the client-id. This is probably because the app you need to create acts as the client.