Authenticate CSOM using authenticated user of Azure AD

Viewed 54

I'm using Azure Ad authentication in my asp.net core application and want to authenticate CSOM using the same user which authenticated using their AD account.

One way is maybe if I acquire the token of the current user and use it with the context of CSOM.

It's very unclear and Microsoft docs aren't helpful either.

Would really appreciate any type of help.

1 Answers

One way can be to use Microsoft.Identity.Client nuget package.

Example (not sure if it will fit your needs), just only for inspiration.

You need to create PublicClientApplication

public IPublicClientApplication CreateClientApp()
{
    var clientApp = PublicClientApplicationBuilder.Create("clientId")
                .WithAuthority($"https://login.microsoftonline.com/{tenantId}")
                .WithDefaultRedirectUri()
                .Build();
    return clientApp;
}

Method for acquiring token

public async Task<string> GetTokenAsync()
{
    // permissions defines in Azure AD
    var scopes = new string[] {"https://<your_tenant_name>.sharepoint.com/<permission_name>"};
    var accounts = await clientApp.GetAccountsAsync();
    var firstAccount = accounts.FirstOrDefault();

    AuthenticationResult authResult;
    try
    {
        authResult = await clientApp.AcquireTokenSilent(scopes, firstAccount).ExecuteAsync();
    }
    catch (MsalUiRequiredException ex)
    {
        authResult = await clientApp
            .AcquireTokenByUsernamePassword(scopes, "userName", "password")
            .ExecuteAsync();
    }
    return authResult.AccessToken;
}

Method for getting ClientContext

public ClientContext GetContext(Uri web)
{
    var context = new ClientContext(web);

    context.ExecutingWebRequest += (sender, e) =>
    {
        string accessToken = GetTokenAsync().GetAwaiter().GetResult();
            e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken;
    };

    return context;
}

Resources:

MSAL

MSAL.NET

Related