Garethp / php-ews

PHP Exchange Web Services
BSD 3-Clause "New" or "Revised" License
112 stars 45 forks source link

UnauthorizedException when connecting to exchange accounts using oauth2 - garethp - php-ews #224

Open ashwindas77 opened 2 years ago

ashwindas77 commented 2 years ago

I use garethp php-ews to connect EWS using oauth2.

I am receiving the access token but when passing it to the mail function (getMailItems,getMailbox,getFolder....etc) following fatal error with "UnauthorizedException" is showing.

Tried many ways but still the same.

`Fatal error: Uncaught garethp\ews\API\Exception\UnauthorizedException in C:\xampp\htdocs\exchange\vendor\garethp\php-ews\src\API\ExchangeWebServices.php:453 Stack trace: #0 C:\xampp\htdocs\exchange\vendor\garethp\php-ews\src\API\ExchangeWebServices.php(368): garethp\ews\API\ExchangeWebServices->handleNonSuccessfulResponses(NULL, 401)

1 C:\xampp\htdocs\exchange\vendor\garethp\php-ews\src\API\ExchangeWebServices.php(301): garethp\ews\API\ExchangeWebServices->processResponse(NULL)

2 C:\xampp\htdocs\exchange\vendor\garethp\php-ews\src\API.php(362): garethp\ews\API\ExchangeWebServices->__call('GetFolder', Array)

3 C:\xampp\htdocs\exchange\vendor\garethp\php-ews\src\API.php(378): garethp\ews\API->getFolder(Array)

4 C:\xampp\htdocs\exchange\vendor\garethp\php-ews\src\Mail\MailAPI.php(22): garethp\ews\API->getFolderByDistinguishedId('inbox')

5 C:\xampp\htdocs\exchange\vendor\garethp\php-ews\src\Mail\MailAPI.php(81): garethp\ews\Mail\MailAPI->getFolderId()

6 C:\xampp\htdocs\exchange\testSync.php(50): garethp\ews\Mail\MailAPI in C:\xampp\htdocs\exchange\vendor\garethp\php-ews\src\API\ExchangeWebServices.php on line 453`

Here are the parameters am passing :

$tokenEndpoint = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
 $authorizationEndpoint = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize';
 $clientId = '********';
 $clientSecret = '********';
 $redirectUri = 'http://localhost/testredirect.php';
 $scope = 'https://outlook.office.com/Mail.Read';

$token = ExchangeWebServicesAuth::getTokenFromAuthorizationCode($clientId, $clientSecret, $code, $redirectUri, $tokenEndpoint);
//Receiving the token correctly

$api = MailAPI::withCallbackToken('outlook.office365.com', $token);
// Here am getting the above mentioned exception. Tried with "$mail = $api->getMailItems();  $api->getFolderByDistinguishedId('inbox'); etc"
$mailbox = $api->getMailbox('inbox'); 
Matt504 commented 1 year ago

Hi @ashwindas77, can you tell us how did you solve your problem, if you did solve it ?