1

I'm currently building a .NET Core App which performs direct SharePoint REST calls to: contoso.sharepoint.com/sites/shipment/_api/search/query?querytext='...'

The .NET Core App is registerd in the Application Registrations. How do I retrieve the Access Token? (For some reason MS Graph API is not able to make these calls, hence trying SPO REST API)

2 Answers 2

1

You could use the certificate way to get the token like this:

    private static async Task<string> GetToken()
    {
        string applicationId = "xxx";
        string tenantId = "contoso.onmicrosoft.com";
        X509Certificate2 certificate = new X509Certificate2(@"C:\certificate.pfx", "password");

        IConfidentialClientApplication confApp = ConfidentialClientApplicationBuilder.Create(applicationId)
        .WithAuthority($"https://login.microsoftonline.com/{tenantId}")
        .WithCertificate(certificate) // This is just a local method that gets the certificate on my machine
        .Build();

        var scopes = new[] { "https://contoso.sharepoint.com/.default" };
        var authenticationResult = await confApp.AcquireTokenForClient(scopes).ExecuteAsync();
        return authenticationResult.AccessToken;
    }
Sign up to request clarification or add additional context in comments.

Comments

0

I'm using the following code for public client application

public async Task<string> GetTokenAsync()
{
    var clientId = "{client_id}";
    var tenantId = "{tenant_id}";
    var instance = "https://login.microsoftonline.com";
    IPublicClientApplication clientApp = PublicClientApplicationBuilder.Create(clientId)
                .WithAuthority($"{instance}/{tenantId}")
                .WithDefaultRedirectUri()
                .Build();

    var accounts = await clientApp.GetAccountsAsync();
    var firstAccount = accounts.FirstOrDefault();

    var scopes = new[] { "https://contoso.sharepoint.com/.default" };
    var userName = "{user}";
    SecureString password = ...;
    AuthenticationResult authResult;
    try
    {
        authResult = await clientApp.AcquireTokenSilent(scopes, firstAccount).ExecuteAsync();
    }
    catch (MsalUiRequiredException ex)
    {
        authResult = await clientApp
                    .AcquireTokenByUsernamePassword(scopes, userName, password)
                    .ExecuteAsync();
    }
    return authResult.AccessToken;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.