Ask Your Question
2

How can Refresh token and Access token be obtained when logging into Azure AD using C#?

asked 2023-05-16 02:12:59 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-16 02:31:02 +0000

bukephalos gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-16 02:12:59 +0000

Seen: 11 times

Last updated: May 16 '23