I working with an MS Graph API to read a user calendar event using Lambda with NodeJs. Here is the flow of what I am doing: First I registered an app in AAD and gave the delegated permission like
Here is the code flow: first I am getting the access token
var options = {
method: 'POST',
url: `https://login.microsoftonline.com/af2601c4-9adasd-******-99fd-e15104d7d9fc/oauth2/v2.0/token`,
data: data(I am passing the clientid, client_secret, scope etc)
};
and after that, I am trying to read the calendar event
try{ const response = await axios.get('https://graph.microsoft.com/v1.0/users/108ca636-***-41e2-8dd5-********/events', {
headers: {
Authorization: `Bearer ${accessToken}`
}
});
but it gives me this error
"message": "Request failed with status code 403",
"name": "AxiosError",
"stack": "AxiosError: Request failed with status code 403
PS: I decoded the Access token and I don't see any permission{in the above picture} I have given in the AAD to the app. thanks in advance.
The error occurred as you are using permissions of Delegated type that won't work with client credentials flow.
Initially, I too got same error when I granted Delegated
permissions and used that token to fetch user's events via Postman:
GET https://graph.microsoft.com/v1.0/users/user_id/events
Response:
To resolve the error, you need to grant permissions of Application type and make sure to grant admin consent like this:
Now, I generated the token again using client credentials flow via Postman with below parameters:
POST https://login.microsoftonline.com/tenantId/oauth2/v2.0/token
grant_type:client_credentials
client_id: appId
client_secret: secret
scope: https://graph.microsoft.com/.default
Response:
You can decode this token in jwt.ms website and check roles
claim for permissions:
When I used this token to fetch user's events with below Graph API call, I got response successfully like this:
GET https://graph.microsoft.com/v1.0/users/user_id/events
Response:
If you want to work with Delegated permissions, make use of interactive flows like authorization code flow.
Reference: Microsoft identity platform and OAuth 2.0 authorization code flow