Using MSAL to get access token and cache it in SQL DB, without having to sign in using MSAL

Related searches

I want to authenticate AAD users to access powerBi resources through MSAL by using application ID and secret. So i want to get the access token and cache it in SQL Db.

went through the documentation but it explains the scenario of using MSAL for sign-in. also went through the tutorial i was able to to do the necessary implementations to get the token.

how can i get the access token and cache it, in a scenario like this?

You can cache the access token (actually, the library does this already), but it is valid for 1 hour only. So it makes no sense to save it in a database, because it will expire quickly.

You should cache the credentials needed to obtain the token (user name and password, app ID and secret, or certificate) and obtain a token when needed.

Acquire & cache tokens with Microsoft Authentication Library (MSAL , Learn about acquiring and caching tokens using MSAL. There are several ways to acquire a token by using the Microsoft Authentication Library (MSAL). MSAL allows you to get tokens to access Azure AD for developers (v1.0) Client credentials flow, which does not use the user token cache but an� Application code should try to get a token from the cache before acquiring a token by another method. This article discusses default and custom serialization of the token cache in MSAL.NET. This article is for MSAL.NET 3.x. If you're interested in MSAL.NET 2.x, see Token cache serialization in MSAL.NET 2.x. Default serialization for mobile

As indicated in other answers, caching tokens are useful in case when you have users signing in, as once the access token expires (typically after 1 hour), you don't want to keep prompting the users to re-authenticate. So help with these scenarios, Azure AD issues a refresh token along with an access token that is used to fetch access tokens once they expire. Caching is required to cache these refresh tokens as they are valid for 90 days.

When an app signs as itself (and not signing in a user), the client credentials flow is used and it only needs the app id (clientId) and the credential (secret/certificate) to issue an access token. The MSAL library will automatically detect when the access token expires and will use the clientId/credential combination to automatically get a new access token. So caching is not necessary.

The sample you should be looking at is this one.

MSAL authentication flows, The Microsoft Authentication Library (MSAL) supports several Enables you to add sign-in and API access to your mobile and desktop apps. Implicit grant, Allows the app to get tokens without performing a back-end server credential You can use the authorization code only once to redeem a token. For more information about this pattern, see Acquire and cache tokens using the Microsoft Authentication Library (MSAL). Authorization code The OAuth 2 authorization code grant can be used in apps that are installed on a device to gain access to protected resources like web APIs.

I'n not sure to understand, I hope these few lines of code will help you.

First, customize token cache serialization :

public class ClientApplicationBuilder
{
    public static IConfidentialClientApplication Build()
    {
        IConfidentialClientApplication clientApplication =
            ConfidentialClientApplicationBuilder
                .Create(ClientId)
                .WithRedirectUri(RedirectUri)
                .WithClientSecret(ClientSecret)
                .Build();

        clientApplication.UserTokenCache.SetBeforeAccessAsync(BeforeAccessNotification);
        clientApplication.UserTokenCache.SetAfterAccessAsync(AfterAccessNotification);

        return clientApplication;
    }

    private static async Task<byte[]> GetMsalV3StateAsync()
    {
        //TODO: Implement code to retrieve MsalV3 state from DB
    }

    private static async Task StoreMsalV3StateAsync(byte[] msalV3State)
    {
        //TODO: Implement code to persist MsalV3 state to DB
    }

    private static async Task BeforeAccessNotification(TokenCacheNotificationArgs args)
    {
        byte[] msalV3State = await GetMsalV3StateAsync();
        args.TokenCache.DeserializeMsalV3(msalV3State);
    }

    private static async Task AfterAccessNotification(TokenCacheNotificationArgs args)
    {
        if (args.HasStateChanged)
        {
            byte[] msalV3State = args.TokenCache.SerializeMsalV3();
            await StoreMsalV3StateAsync(msalV3State);
        }
    }
}

Here's an example to acquire token (by Authorization Code) :

public class MsAccountController
    : Controller
{
    private readonly IConfidentialClientApplication _clientApplication;

    public MsAccountController()
    {
        _clientApplication = ClientApplicationBuilder.Build();
    }

    [HttpGet]
    public async Task<IActionResult> Index()
    {
        Uri authorizationRequestUrl = await _clientApplication.GetAuthorizationRequestUrl(ClientApplicationHelper.Scopes).ExecuteAsync();
        string authorizationRequestUrlStr = authorizationRequestUrl.ToString();
        return Redirect(authorizationRequestUrlStr);
    }

    [HttpGet]
    public async Task<IActionResult> OAuth2Callback(string code, string state)
    {
        AuthenticationResult authenticationResult = await _clientApplication.AcquireTokenByAuthorizationCode(scopes, code).ExecuteAsync();
        return Ok(authenticationResult);
    }
}

Finally, acquire a token silently and use auth result for your API client :

public class TaskController
    : Controller
{
    private readonly IConfidentialClientApplication _clientApplication;

    public TaskController()
    {
        _clientApplication = ClientApplicationBuilder.Build();
    }

    [HttpGet]
    public async Task<IActionResult> Index()
    {
        IEnumerable<IAccount> accounts = await _clientApplication.GetAccountsAsync();
        AuthenticationResult result = await _clientApplication.AcquireTokenSilent(ClientApplicationHelper.Scopes, accounts.FirstOrDefault()).ExecuteAsync();

        //TODO: Create your API client using authentication result
    }
}

Regards

Fetch An Access Token To Access Microsoft Graph API Using Msal , Once you click register, you can get the unique client id/client secret for the app you registered. It requires configuring MSAL JS to validate and� In Our application uses AAD for authenticating the corporate users within our organization only. Is that possible to set the response type as access token instead of default id_token ?

Msal get access token from cache, Examples of such data include a result of a query to a database, a disk file or a report. While MSAL For Azure AD B2C, checkout how to register your app with B2C. What I need is •None when there is simply no token in the cache. 0) signing-in I use the following link to get a new access token: Authentication with Msal. AcquireTokenSilentAsync is the process by which refresh_token is used to get new access_token, but, this is internally done. See AcquireTokenSilentAsync using a cached token for more details and other access patterns. Hope this clarifies on why TokenCache is the 'new' refresh_token in MSAL.NET, and TokenCache is what you would need to serialize

Error : No account or login hint was passed to the , On the sql token caching, I ran into a different issue when trying to run multiple instead of accessing them from independently deployed apps running on a server but I I've encountered far more issues that i'd have like when using MSAL. The customization of token cache serialization to share the SSO state between ADAL.NET 3.x, ADAL.NET 5.x, and MSAL.NET is explained in part of the sample active-directory-dotnet-v1-to-v2. Simple token cache serialization (MSAL only) The following example is a naive implementation of custom serialization of a token cache for desktop applications.

If you call Get-MsalToken and the existing token in the token cache is still valid then the Access Token from the token cache is returned. If it has expired a new Access Token will be obtained. If you want to force the cmdlet to get a new Access Token, you can by using the Clear-MsalCache cmdlet from the MSAL.PS module or using the

Comments
  • the reason i need to cache the token in a persistent storage is because we are using the master user's access token for other normal users. so for an example user A can be the master user with powerBI access and user B can be a normal user who can just view reports. so user A adds the powerbi instance and reports to the application and authenticate himself and allow user B to view the reports within the application. So user B views the reports with the access token of user A. The application sign-in authentication is independent. This is to authenticate users to access PowerBI resources
  • any thoughts on this ?
  • the reason i need to cache the token in a persistent storage is because we are using the master user's access token for other normal users. so for an example user A can be the master user with powerBI access and user B can be a normal user who can just view reports. so user A adds the powerbi instance and reports to the application and authenticate himself and allow user B to view the reports within the application. So user B views the reports with the access token of user A. The application sign-in authentication is independent. This is to authenticate users to access PowerBI resources.
  • any thoughts on this ?