23

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?

Marc LaFleur
  • 31,987
  • 4
  • 37
  • 63
Hugo Hilário
  • 2,848
  • 2
  • 27
  • 43

4 Answers4

35

There are two pieces required to enable Refresh Tokens:

  1. You need to request the scope offline_access. This tells the endpoint to provide a refresh_token alongside the access_token and associated metadata.

  2. 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.

Marc LaFleur
  • 31,987
  • 4
  • 37
  • 63
  • Thanks a lot. I will try that. It's a pity that we don't have a method for that on the Microsoft.Graph Library. Still I will do the http request like you say. The redirect_uri does not make that much sense since I will be doing the call from the backend, although I assume I need to send the same value I had previously defined on the Microsoft Developer console. – Hugo Hilário Jul 04 '18 at 09:00
  • 2
    Do you happen to have a link to some c# code showing how to get a refresh-token or is this possible only by calling the API manually with an http-client? – t3chb0t Oct 01 '21 at 15:38
  • Everytime this request returns new refresh token. Do these refresh tokens have fresh 90 day lifetime ? Or I will have to relogin anyway after 90 days? – Rihard Novozhilov Mar 04 '23 at 00:50
  • Each refresh of the auth token also generates a new refresh token. The new refresh token will expire 90 days from the time it was generated. – Marc LaFleur Mar 08 '23 at 00:32
5

This helped me, when i was not having refreshToken https://learn.microsoft.com/en-gb/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow

POST /oauth2/v2.0/token HTTP/1.1 Host: login.microsoftonline.com 
Content-Type: application/x-www-form-urlencoded

grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer  
&client_id=2846f71b-a7a4-4987-bab3-760f389 
&client_secret=BYyVnAt56JpLwUcyo47XODd 
&assertion=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIs...pa970UvdVfQ 
&scope=https://graph.microsoft.com/user.read+offline_access 
&requested_token_use=on_behalf_of

sample response:

{
    "token_type": "Bearer",
    "scope": "User.Read Mail.Read Mail.Send Calendars.Read",
    "expires_in": 3600,
    "ext_expires_in": 3600,
    "access_token": "EwCAA8l6BAAUO9chh8cJscQLmU+LSWpbnr0v...ZgNcrJkgI=",
    "refresh_token": "MCS3KUzqyCY6rQH*NXLSLQctqj47w...x3Oa4r"
}
1

below shell-scirpt worked for me for renewing access_token using refresh_token of MS-Graph/Azure-AD

# SCRIPT BEGINS FROM HERE #
echo "SCRIPT EXECUTION BEGINS"
echo " "
echo "Script to  request new access token and refresh token from refresh token of MS-Graph apis"
echo " "
echo "You can also follow this links for reference" 
echo "https://www.youtube.com/watch?v=FTULjLL-ZDI"   
echo "https://dzone.com/articles/getting-access-token-for-microsoft-graph-using-oau-1" 
echo " "
echo "If don't know your Azure-AD-Tenant-Name then just follow this below link to get it"
echo "https://helpdesk.kaseya.com/hc/en-gb/articles/115002521251-How-Do-I-Find-My-Azure-AD-Tenant-Name-"
echo " "
read -p "Enter your Tenant name : " tenant
echo "Tenant named your entered is: $tenant "

echo " "
read -p "Enter your client_id: " client_id
echo "Client_id you entered is: $client_id"

echo " "
read -p "Enter your client_secret: " client_secret
echo "Client_secret you entered is: $client_secret"

echo " "
read -p "Enter your redirect_uri (eg. http://localhost): " redirect_uri
echo "redirect_uri you entered is: $redirect_uri"

echo " "
echo "Enter the refresh_token value you haved copied from postman"
read -p "Enter your refresh token: " refresh_token
echo " "
echo "Refresh_token: " $refresh_token


authorization_endpoint=$(curl -s  "https://login.microsoftonline.com/${tenant}/v2.0/.well-known/openid-configuration" | jq -r '.authorization_endpoint')
token_endpoint=$(curl -s  "https://login.microsoftonline.com/${tenant}/v2.0/.well-known/openid-configuration" | jq -r '.token_endpoint')

echo " "
echo "Authorize endpoint of your tenant is"
echo "$authorization_endpoint"

echo " "
echo "Token endpoint of your tenant is"

echo "$token_endpoint"


#token=$(curl -H "Content-Type: application/application/x-www-form-urlencoded" -X POST "https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"   --data-urlencode 'client_id=63bf591a-e1c' --data-urlencode 'client_secret=WUR-AH-7ML1fSHT_oH6HVVA8Jd' --data-urlencode 'redirect_uri=http://localhost'  --data-urlencode 'grant_type=refresh_token' --data-urlencode 'refresh_token=$refresh_token' --data-urlencode 'scope=https://graph.microsoft.com/.default' --data-urlencode 'tenant=$tenant' )

#token=$(curl -s -X POST "$token_endpoint" --header "Content-Type: application/x-www-form-urlencoded" --data-urlencode "client_id=45789-87a3-cbb1d1076b3b" --data-urlencode "client_secret=_oH6HVVA8Jd5p9OCa-S" --data-urlencode "redirect_uri=http://localhost" --data-urlencode "grant_type=refresh_token" --data-urlencode "refresh_token=$refresh_token" --data-urlencode "scope=openid profile offline_access  https://graph.microsoft.com" --data-urlencode "tenant=$tenant" | jq .access_token)

token=$(curl -s -X POST "$token_endpoint" --header "Content-Type: application/x-www-form-urlencoded" --data-urlencode "client_id=$client_id" --data-urlencode "client_secret=$client_secret" --data-urlencode "redirect_uri=$redirect_uri" --data-urlencode "grant_type=refresh_token" --data-urlencode "refresh_token=$refresh_token" --data-urlencode "scope=openid profile offline_access https://graph.microsoft.com/.default" --data-urlencode "tenant=$tenant" | jq .access_token)
echo " "
echo "Your renewed access token is:"
echo " "
echo "$token"
echo " "
echo "SCRIPT ENDS"

# SCRIPT ENDS HERE


devops-admin
  • 1,447
  • 1
  • 15
  • 26
-2

There is a way to do this, but it is only recommended for ADAL.NET 2.x to MSAL.NET 2.x migration scenarios, which is outlined here: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/Adal-to-Msal

Only for client credentials (not auth code).