2
votes

I'm implementing the Microsoft Graph APIs using the Client Credentials Grant Flow, as explained at https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_service. Also, the app was registered at https://apps.dev.microsoft.com/.

The aim here is to allow our web application to perform actions like checking the calendars of our users and sending mail on their behalf, without each user being required to authenticate and grant access to the application. The idea is to make it transparent to them.

So I think I've got it working, but wanted to clarify a few things.

  • Once the admin consent is granted, does it ever need to be done again if the permissions for the application don't change?
  • When requesting an access token, it looks like it expires in an hour. Is there a way to make that longer? Otherwise, what is a typical workflow like to ensure the token isn't expired? Should I be requesting a token each time the application is making an API request to ensure the token is valid? Or perhaps store the token, but get a new one before it expires?
1

1 Answers

1
votes

Admin Consent only provides consent for the permissions that were registered at the time consent was granted. So yes, if you change permissions you will also need to repeat Admin Consent before your application will receive the new scopes.

An Access Token only lives for a short period of time by design. You shouldn't request a new token with every request since that adds needless overhead. Instead, you should request a new token only after it has expired.

The response from AAD that contains your token will also provide the expiration time:

{
  "access_token": "eyJ0eXAiOiJKV1QiLCJ...",
  "expires_in": 3599,
  "token_type": "Bearer",
  "scope": "https://graph.microsoft.com/mail.read https://graph.microsoft.com/user.read",
}

You can hydrate the token response into an object along with the time the object was created. Before making a call to the Graph, you check the expiration time to determine if your app needs to refresh the token beforehand.