I am working on ASP.Net MVC classic application. This app get a access token to gain access the resource in the API. Once it get the access token then I want to store it and use it when I need it to call the API in different controller. However, I want to :
Store, retrieve and refresh and want to have understanding of AcquireTokenSilently().
We may get the token after user sign-in in Startup.cs and then it can be saved and retrieve to access API. So, it might be checked for expire token and then refresh or acquire token silently to access API resource. So whatever flow makes sense.
I have read several document for MSAL but did not get the clear picture and getting confused by AcquireTokenSilently(), Refresh(). Please see the below code where I am accessing token but I am not storing it.
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
{
notification.HandleCodeRedemption();
var idClient = ConfidentialClientApplicationBuilder.Create(clientId)
.WithRedirectUri(redirectUri)
.WithClientSecret(clientSecret)
.WithAuthority(authority)
.Build();
try
{
var apiScope = "api://28178a67-4ae6-43d4-b708-c02785516b1d/asses_as_users api://28178a67-4ae6-43d4-b708-c02785516b1d/AzAdUtility.Get";
string[] scopes = apiScope.Split(' ');
var result = await idClient.AcquireTokenByAuthorizationCode(
scopes, notification.Code).ExecuteAsync();
}
catch (Exception ex)
{
string message = "AcquireTokenByAuthorizationCodeAsync threw an exception";
notification.HandleResponse();
notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
}
}
Update This link below guided me to implement the token cache in MVC.NET classic. I do have some issues but I did get the idea of caching token.
Note: The issue is related to the dev environment when the program is stopped from Visual Studio or browser window is closed the cache is seem to be missing.
https://github.com/Azure-Samples/ms-identity-aspnet-webapp-openidconnect