Search code examples
c#azureazure-active-directory

Get refresh token additionally to access token with Microsoft.Identity.Client


I use several properties like tenant id, client id, client secret, redirect uri and an authorization code generated for a user. I need to get the access and refresh token, but with the API that don't return anything like a refresh token. I need a refresh token additionnally to the access token and the expire in time. I use this following code:

ConfidentialClientApplicationOptions options = new ConfidentialClientApplicationOptions();
        options.ClientId = clientId;
        options.TenantId = tenantId;
        options.ClientSecret = clientSecret;
        options.RedirectUri = redirectUri;

        ConfidentialClientApplicationBuilder builder = ConfidentialClientApplicationBuilder.
            CreateWithApplicationOptions(options);
        IConfidentialClientApplication app = builder.Build();
        AcquireTokenByAuthorizationCodeParameterBuilder acquireTokenBuilder = 
            app.AcquireTokenByAuthorizationCode(ServiceConstants.ALL_SCOPE_AUTHORIZATIONS.Split(' '), authorizationCode);
        AuthenticationResult result = await acquireTokenBuilder.ExecuteAsync();
        string accessToken = result.AccessToken;
        // NO string refreshToken = result.RefreshToken

Its very strange because in several example, I see the RefreshToken available in AuthenticationResult, but not in mine. Do you know why ? And how I can get the refresh token plz ?

Because after that I will need to refresh the access token when will expire and I only have the access token, tenant id, client id, secret (or certificate) and redirect uri. BTW How to regenerate it after access token expiration ?

thank a lot and best regards

Adrien


Solution

  • You need to check what is passed as ServiceConstants.ALL_SCOPE_AUTHORIZATIONS in both /authorize and /token requests. The list of scopes should contain offline_access scope as it tells Azure that your application will need a refresh token for extended access to resources.

    The refresh token will have a longer lifetime than the access token, therefore whenever your access token expires you will be able to call the /token endpoint again providing the previously received refresh token and using the parameter grant_type=refresh_token.