I'm connecting to the Microsoft Graph using:
public GraphServiceClient GetAuthenticatedClient(string token)
{
GraphServiceClient graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
// Append the access token to the request.
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}));
return graphClient;
}
I'm running this code on the server. The token I'm using is being sent to me by an external App.
Everything works great during the first hour, then the token expires.
My question is : How can I get a new token, since I also have access to the refresh token?
To refresh your access token as well as an ID token, you send a token request with a grant_type of refresh_token . Be sure to include the openid scope when you want to refresh the ID token. If the refresh token is valid, then you get back a new access and the refresh token.
Refresh token lifetime The default lifetime for the refresh tokens is 24 hours for single page apps and 90 days for all other scenarios. Refresh tokens replace themselves with a fresh token upon every use. The Microsoft identity platform doesn't revoke old refresh tokens when used to fetch new access tokens.
Because OAuth2 access expires after a limited time, an OAuth2 refresh token is used to automatically renew OAuth2 access. Click the tab for the programming language you're using, and follow the instructions to generate an OAuth2 refresh token and set up the configuration file for your client.
There are two pieces required to enable Refresh Tokens:
You need to request the scope offline_access
. This tells the endpoint to provide a refresh_token
alongside the access_token
and associated metadata.
You need to request a new access_token
(and refresh_token
as they come together) by repeating the same POST
to /common/oauth2/v2.0/token
with a slightly different body - grant_type
is set to refresh_token
and instead of a code
, you supply a refresh_token
property and value:
https://login.microsoftonline.com/common/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded
grant_type=refresh_token&
refresh_token=[REFRESH TOKEN]&
client_id=[APPLICATION ID]&
client_secret=[PASSWORD]&
scope=[SCOPE]&
redirect_uri=[REDIRECT URI]
A while back I wrote up a show primer on the v2 Endpoint that you might find helpful as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With