Search code examples
phplaravelazure-active-directorymicrosoft-graph-apimicrosoft-entra-id

How to use user's access token or access token based on Tenant ID in Microsoft graph API?


enter image description here enter image description here Here are the methods I tried using the Microsoft Graph API and their respective outcomes:

Method 1:

  • After Single Sign-On (SSO), we obtain an access token.
  • This access token is used as a bearer token for Graph API integration.
    public function redirectToMicrosoft(){
        return Socialize::driver('graph')->scopes(['offline_access'])->redirect();
        }

    public function handleMicrosoftCallback(){   
        $user = Socialize::driver('graph')->user();
        return $user->access_token;
    }

Method 2:

  • Obtaining an access token based on the tenant ID and specified parameters.
  • Using the obtained access token.

    public function getAccessToken()
    {
        $tenantId = env('MICROSOFT_TENANT_ID');
        $clientSecret = env('MICROSOFT_CLIENT_SECRET');
        $clientId = env('MICROSOFT_CLIENT_ID');        
    
        $input = [
            'grant_type' => 'client_credentials',
            'client_id' => $clientId,
            'scope' =>"https://graph.microsoft.com/.default",
            'client_secret' => $clientSecret,
        ];
      
        $client = new Client();
        $response = $client->request('POST', "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token", ['form_params' => $input]);
     
        $statusCode = $response->getStatusCode();
        $responseBody = json_decode($response->getBody(), true);
    
        $this->accessToken = $responseBody['access_token'];
        return $responseBody;
    }

UPDATE:

Kindly find the permission below, enter image description here

When attempting to sign in with an Azure AD-configured email, which involves registering an email address to obtain a client and secret. I get the code and the access token API works fine.

enter image description here

When attempting to sign in with different outlook mail, I get the below error. Please refer the screenshot,

enter image description here

CODE 0.AS4AgI6YLYeIu0eXbgo3fHk6PszspcPofddJs-W7b5ajEO-5AC8.AgABAAIAAAAmoFfGtYxvRrNriQdPKIZ-AgDs_wUA9P-kBJSNPkGJJsNJgB510cZ69mO3JTSYLh89i4PpBhv1Y8L0nk51BFcTUh7bEe2i5dC24W1eeEqsOCuGKJcUYbmfdHCKHkpnaUBAFoHsIGhyydpHwMvezF4pAnL8_-OxgJeM-xPaj3WFxqZfEvwP6R4TFxQ4IP5hovS1erTxlMCS63dA9hdL7jbkpDHjrp3wgqs01zRt_q5RAPCH4KtRGtirnMnll-3PSEkcLixKUQkeC261Z_0JsK5aGRidAv0IFNs_nw5cPtowTEuEiv99EJZQLJbt7qLOhz0DIPBBeBhpJl2bi6OsdOV4UZ59eQafOEanxA-5_pC6gy3H3nc9kiVfPddlneBXKGbFbaoXHyl9hi_i7bzNcJDubNteM2TQETYy7VgnoRpNEbh_eOZNV4T1rVtr8h5F4fxg9MaWkmQog8s9dxtDwY4MCYq9UBb1tVTeOlm38w3oyQWR-3ZCbD8wV4IZV3TEzrqJfhURm8E_cgcgTLdzOm-8uK9f-E0NAC4aodqXf_V3d8wLtR6QJi-WNOKlB-8THR-WNuMZvBcZiL38h_zToPbgwnL0fSRfsuoU57kwE8t30HpcDzRq2PilxgdDjoGolStRNEv-RDrgTS-66EewjHevBwbU_5A0nSfNzjhksl5NQfuEdnoRSZ3QTH4jwLgzIZ3aSkwphkoRtDJRa_Ri1U8PdAzolRl2SlJIYp7sqvIfpPL9SSRgEA6ftusb8seE9gEcGXKvvRFEQza4KgrsC9NHNMQunJFlQxbb5Y1SpdgRWC9BsK7oIGgegj5F4CKoBgKqlaOmis2I_QvZxVil5KSq4zft&state=12345&session_state=9c29347d-1351-48c8-90dc-c1ab380a6221


Solution

  • Note that, you cannot fetch personal Outlook calendar events using token generated with client credentials flow.

    You need to switch to delegated flows like authorization code flow by granting delegated permissions with /common endpoint.

    In my case, I registered one multi-tenant application with below account type that allows both organizational and personal Microsoft accounts:

    enter image description here

    Now, I granted Calendars.ReadWrite permission of Delegated type in that application as below:

    enter image description here

    Initially, I ran below authorization request in browser that displayed consent screen after signing in:

    https://login.microsoftonline.com/common/oauth2/v2.0/authorize? 
    client_id=appId
    &redirect_uri=https://jwt.ms
    &response_type=code  
    &response_mode=query  
    &scope=https://graph.microsoft.com/.default
    &state=12345
    

    enter image description here

    After accepting the consent, I got authorization code value in address bar:

    enter image description here

    Now, I generated access token using authorization code flow via Postman with below parameters including code value:

    POST https://login.microsoftonline.com/tenantId/oauth2/v2.0/token
    grant_type: authorization_code
    client_id: appId 
    client_secret: secret 
    scope: https://graph.microsoft.com/.default
    code: paste_code_from_above
    redirect_uri: https://jwt.ms
    

    Response:

    enter image description here

    When I used this token to fetch events of personal outlook calendar user, I got the response successfully as below:

    GET https://graph.microsoft.com/v1.0/me/events
    

    Response:

    enter image description here

    If you are trying to list or create events in normal Azure AD user account, make sure to assign an active Office 365 license to the user.

    UPDATE:

    Note that, the error Invalid request. Request is malformed or invalid usually occurs if you are passing invalid values in token parameters.

    I got the same error when passed invalid or extra characters in code parameter while generating token like this:

    enter image description here

    To resolve the error, you should remove this part &state=12345&session_state=9c29347d-1351-48c8-90dc-c1ab380a6221 from code parameter

    Your valid code value should be this:

    enter image description here