Search code examples
oauthazure-active-directorysingle-page-applicationmicrosoft-entra-id

Do I use ID token or access token while calling a backend API?


From Azure AD documentation I understand that ID token is for authentication and access token is what you send to the backend API for authorization.

But I have several APIs which gives response based on the roles of the user who is logged in. I have configured the roles in the Service Principal under App roles as seen in the below picture.

enter image description here

And when the user authenticates, the ID token contains the roles as seen below.

enter image description here

Currently, I send the ID token in the Authorization header and then the backend decodes and validates the token and based on the roles, it sends appropriate response.

But I was not able to find any documentation to justify this solution. If there is a better/proper solution on how to implement this, please do guide me! Or is there a way to send roles from access token?


Solution

  • You have to make use of access token to call the backend API. Refer to this blog by Maria Paktiti.

    If you want the roles to be present in access token, then try the steps below:

    Create a Microsoft Entra ID application and added an app role:

    enter image description here

    Then assign the role to the user in your Enterprise application:

    enter image description here

    And grant API permissions:

    enter image description here

    Then generate access and ID tokens like below:

    https://login.microsoftonline.com/TenantID/oauth2/v2.0/token
    
    client_id:ClientID  
    scope:api://ID/.default openid offline_access
    grant_type:authorization_code  
    code:code  
    redirect_uri:https://jwt.ms
    client_secret:Secret
    

    When you decode the access token, the role is displayed:

    enter image description here

    Even in the ID token the role is displayed:

    enter image description here

    Hence, to have role-based authorization you can make use of access token.