adal to msal migration

Viewed 46

I am working on an old codebase which is using ADAL silent token acquire and I need to update it to MSAL.

the code looks like this:

public static async Task<string> AcquireToken(string userObjectId)
        {
            ClientCredential cred = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.ClientSecret);
            string tenantId = ClaimsPrincipal.Current.FindFirst(Globals.TenantIdClaimType).Value;
            AuthenticationContext authContext = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, ConfigHelper.AadInstance, tenantId), new TokenDbCache(userObjectId));
            AuthenticationResult result = await authContext.AcquireTokenSilentAsync(ConfigHelper.GraphResourceId, cred, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
            return result.AccessToken;
        }

        public static async Task<string> AcquireToken(string resource, string userObjectId)
        {
            ClientCredential cred = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.ClientSecret);
            string tenantId = ClaimsPrincipal.Current.FindFirst(Globals.TenantIdClaimType).Value;
            AuthenticationContext authContext = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, ConfigHelper.AadInstance, tenantId), new TokenDbCache(userObjectId));
            AuthenticationResult result = await authContext.AcquireTokenSilentAsync(resource, cred, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
            return result.AccessToken;
        }

I am trying to read documents but for the life of me can't figure out how to go about it.

any help?

cheers

1 Answers

This is my implementation for retrieving the access token interactively (the first time) and silently renewing the token without the user's interaction:

private static AuthenticationResult InitializeToken(EWSConnectionParameters param)
    {
        if (param.OAuthCredentials==null)
            throw new UnauthorizedAccessException("OAUTH credentials not present");

        var clientID = param.OAuthCredentials.ClientId;
        var tenantId = param.OAuthCredentials.TenantId;
        var instance = param.OAuthCredentials.Instance;
        string[] scopes = param.OAuthCredentials.Scopes;

        AuthenticationResult authResult = null;

        IPublicClientApplication publicApp = PublicClientApplicationBuilder.Create(clientID)
                        .WithAuthority($"{instance}{tenantId}")
                        .WithDefaultRedirectUri()
                        .Build();
        TokenCacheHelper.GetInstance().EnableSerialization(publicApp.UserTokenCache);

        var accounts = publicApp.GetAccountsAsync().Result;
        var firstAccount = accounts.FirstOrDefault();

        try
        {
            //first try to silently get the token
            authResult = publicApp.AcquireTokenSilent(scopes, firstAccount)
                .ExecuteAsync().Result;
            TraceWriter.Write(typeof(EwsProxyFactory), "InitializeToken", "The authentication token was acquired silently. Expiration time: " + authResult.ExpiresOn.DateTime.ToString());
        }

        catch (MsalUiRequiredException ex)
        {
            // A MsalUiRequiredException happened on AcquireTokenSilent, meaning that the token couldn't be acquired silently
            TraceWriter.Write(typeof(EwsProxyFactory), "InitializeToken", "Failed to acquire the authentication token silently. The user needs to authenticate itself.");
           
            //todo: create custom exception 
            throw new UnauthorizedAccessException("Token expired but running in silent mode");
        }
        catch (Exception ex)
        {
            TraceWriter.Write(typeof(EwsProxyFactory), "InitializeToken", "Error Acquiring Token Silently: " + ex);
            throw;
        }

        TraceWriter.Write(typeof(EwsProxyFactory), "InitializeToken", "Token acquired");
        return authResult;
    }

and this is for the interactive login:

authResult = await publicApp.AcquireTokenInteractive(scopes)
                        .WithAccount(accounts.FirstOrDefault())
                        .WithPrompt(Prompt.SelectAccount)
                        .ExecuteAsync();
Related