Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To obtain Refresh token and Access token when logging into Azure AD using C#, you can use the Microsoft Authentication Library (MSAL) for .NET. Here are the steps:

  1. Install the Microsoft.Identity.Client package from NuGet.

  2. Use the following code to create a public client application:

var pca = PublicClientApplicationBuilder.Create(clientId)
                    .WithAuthority(authority)
                    .WithRedirectUri(redirectUri)
                    .Build();

Here, the clientId is the client ID of your Azure AD application, the authority is the Azure AD endpoint for authentication, and the redirectUri is the URI to which the authentication response will be sent.

  1. Use the following code to acquire a token interactively:
var scopes = new[] { "user.read" };
var accounts = await pca.GetAccountsAsync();
var result = await pca.AcquireTokenInteractive(scopes).WithAccount(accounts.FirstOrDefault()).ExecuteAsync();

Here, the scopes are the permissions you want to request, accounts is a list of accounts available on the device, and the result is an AuthenticationResult object that contains the Access token, Refresh token, and other authentication details.

  1. Use the following code to acquire a token silently using a Refresh token:
var accounts = await pca.GetAccountsAsync();
var result = await pca.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync();

Here, the scopes and accounts are the same as before. The result object will contain a new Access token (if the Refresh token is valid) and the same Refresh token.

Note that you need to store the Refresh token securely for later use. You can use it to obtain a new Access token when the current token expires or when the user logs out and logs back in.