How to refresh the access token of Microsoft Graph API in Laravel | Ms Graph API Access Token Expired or not

How to refresh an access token for Microsoft Graph API and also check is AccessToken expired or not?


In this post, you will be learning to refresh an access token of the MS Graph API and also we will see how to check the Access Token is expired or not. 

To check or refresh the AccessToken of MS Graph API you to first get the access token: Click here: How to get Access Token of Ms Graph API in Laravel

Step 1: Create a Controller named MsGraphController.php and paste the below code:

<?php

namespace App\Http\Controllers\Api\V1\MicrosoftGraph;

use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\MsGraphToken;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;

class MsGraphController extends Controller
{
    public function checkIsAccessTokenExpired()
    {
        $user = Auth::user();
        if(!$user->msGraphToken){
            return response()->json([
                'error' => 'no_access_token',
                'data' => 'no_access_token',
                'message' => 'You do not have an MS Graph API - Access Token',
            ]);
        }

        // Check if the access token is expired
        if (strtotime($user->msGraphToken->expiry_time) < time()) {

            $refreshToken = $user->msGraphToken->refresh_token;

            // If AccessToken is expired, then refresh the access_token
            $newAccessToken = Http::asForm()->post('https://login.microsoftonline.com/'.env('MICROSOFT_TENANT_ID').'/oauth2/v2.0/token', [
                                    'client_id' => env('MICROSOFT_CLIENT_ID'),
                                    'client_secret' => env('MICROSOFT_CLIENT_SECRET'),
                                    'refresh_token' => $refreshToken,
                                    'grant_type' => 'refresh_token',
                                ]);

            if($newAccessToken->successful()){

                // Update the database with the new access token details
                MsGraphToken::where('user_id', Auth::user()->id)->update([
                    'access_token' => $newAccessToken['access_token'],
                    'refresh_token' => $newAccessToken['refresh_token'],
                    'expires_in' => $newAccessToken['expires_in'],
                    'expiry_time' => Carbon::now()->addSeconds($newAccessToken['expires_in']),
                ]);

                return response()->json([
                    'data' => 'token_validated',
                    'message' => 'New Authentication Successful',
                ]);

            }else{

                $errorMessage = $newAccessToken->json();
                return response()->json([
                    'message' => 'Something Went Wrong!. While Refreshing Token: '. $errorMessage,
                    'data' => 'invalid_refresh_token',
                    'error' => 'error',
                ]);
            }

        }else{

            return response()->json([
                'data' => 'token_validated',
                'message' => 'Authentication successful',
            ]);
        }
    }
}


Step 2: Create an API in following path: routes/api.php

use App\Http\Controllers\MsGraphController;

Route::prefix('v1/ms-graph')->group( function () {

    Route::post('/auth-check', [MsGraphController::class, 'checkIsAccessTokenExpired']);

});


That's it. You can use this API to refresh the Ms Graph API Access Token.