'How to store and retrieve Access Token using MSAL in MVC.net
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
Solution 1:[1]
You don't store it. MSAL does. It has a token cache built in to it. This cache is application specific so that it will need to acquire a token the first time each application is run. You can also use a Broker to pull a token from the OS that is associated with the current user logged on.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | HackSlash |
