TheNetworg / oauth2-azure

Azure AD provider for the OAuth 2.0 Client.
https://packagist.org/packages/thenetworg/oauth2-azure
MIT License
230 stars 108 forks source link

Trouble using scope Mail.Send with permissions #135

Closed jordm closed 2 years ago

jordm commented 3 years ago

I am just starting to learn this so I apologize if I'm butchering the implementation. When trying to use Mail.Send scope and am met with this error:

invalid_grant AADSTS65001: The user or administrator has not consented to use the application with ID

although I've consented to all permissions through azure portal -> app registration -> api permissions as well as azure portal-> enterprise applications -> permissions.

Untitled

I have users sign in using v2.0 and save the token in $_SESSION['aToken'] and the refresh token in $_SESSION['rToken']

When calling my sendmail script I include my provider file

<?php
require_once __DIR__. '/../../vendor/autoload.php';
if (!isset($_SESSION)) session_start();

$provider = new TheNetworg\OAuth2\Client\Provider\Azure([
    'clientId'                => redacted,
    'clientSecret'    => redacted,
    'redirectUri'      => 'http://localhost:8000/oauth.php',
    'defaultEndPointVersion' => '2.0',
]);

and in sendmail:

<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/classes/provider.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/load.php';

$provider->scope = 'User.Read Mail.Send offline_access';

try{    
$provider->urlAPI = 'https://graph.microsoft.com/';
$accessToken = $provider->getAccessToken('refresh_token', [
    'refresh_token' => $_SESSION['rToken'],
    'scope' => $provider->scope,
]);

echo "<pre>";
echo("Token: ".$accessToken."\n\n");
echo("Token: ".$_SESSION['rToken']."\n\n");
echo "</pre>";

$me = $provider->get($provider->getRootMicrosoftGraphUri($accessToken) . '/v1.0/me', $accessToken);

// $body = '{}';

// send mail
// $send = $provider->post($base . '/v1.0/', $accessToken);
}catch(\Exception $e){
    echo $e->getMessage();
}

When removing the mail.send scope $me has all expected variable

decomplexity commented 3 years ago

When trying to send, try using a scope of only ‘https://outlook.office.com/SMTP.Send' If you use scopes that are specifically Graph such as User.Read or Mail.Send, MSFT tries to use the Graph API resource rather than outlook.office.com and fails. Your error may be a side-effect of this.

hajekj commented 3 years ago

I probably spotted the issue, you are using Mail.Send with Application-level permissions, not delegated in your AAD: image

decomplexity commented 3 years ago

Pls ignore my earlier comment. I had assumed you were wishing to OAUTH2 authenticate for SMTP sending and had used Graph's Mail.Send in the scope - which combination doesn't work as the resource that implements OAUTH2-authenticated SMTP is the Exchange API and not Graph and you cannot mix resources in one authorisation token.