Goga
Goga

Reputation: 73

How to create GraphServiceClient?

I'm developing Windows form app using Microsoft Graph API. Does anyone know how to get an access token and how to create GraphServiceClient?

Upvotes: 3

Views: 7668

Answers (3)

Anil
Anil

Reputation: 700

Since DelegateAuthenticationProvider is no longer available in Graph v5, here is an updated solution involving IAccessTokenProvider as seen in the Integrated Windows provider example.

public class TokenProvider : IAccessTokenProvider
{
    public AllowedHostsValidator AllowedHostsValidator => throw new NotImplementedException();

    public async Task<string> GetAuthorizationTokenAsync(Uri uri, Dictionary<string, object>? additionalAuthenticationContext = null, CancellationToken cancellationToken = default)
    {
        // Fetch token here
        string token = "token";
        return token;
    }
}

With this, you can instantiate the client:

var authenticationProvider = new BaseBearerTokenAuthenticationProvider(tokenProvider);
GraphServiceClient graphService = new GraphServiceClient(authenticationProvider);

To retrieve an access token, Microsoft recommends authenticating the user with MSAL.NET.

Upvotes: 0

Fabian
Fabian

Reputation: 31

The graphClient gets the access token for you, you can also do it yourself using httpClient, but if you do it like this you have to pass the clientSecretCredentials to the graphClient. Mine are stored within the Settings-class.

private readonly GraphServiceClient graphClient;

    internal Service()
    {
        ClientSecretCredential clientSecretCredential = new(
            Settings.TenantId,
            Settings.ClientId,
            Settings.CLientSecret,
            new ClientSecretCredentialOptions() { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud });

        graphClient = new GraphServiceClient(clientSecretCredential, Settings.Scopes);
    }

The settings class looks like this:

internal static class Settings
{
    internal const string ClientId = "my_client_id";
    internal const string TenantId = "my_tenant_id";
    internal const string CLientSecret = "my_client_secret";
    internal static string[] Scopes = { "https://graph.microsoft.com/.default" };
}

Upvotes: 3

Shweta Lodha
Shweta Lodha

Reputation: 98

private async Task<string> GetAccessToken()
        {
            IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(APP_ID)
              .WithClientSecret(APP_SECRET)
              .WithAuthority($"https://login.microsoftonline.com/{TENANT_ID}")
              .WithRedirectUri("https://localhost")
              .Build();

            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

            var result = await app.AcquireTokenForClient(scopes).ExecuteAsync();

            return result.AccessToken;
        }

private GraphServiceClient GetGraphClient()
        {
            var graphClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) => {
                // get an access token for Graph
                var accessToken = GetAccessToken().Result;

                requestMessage
                    .Headers
                    .Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                return Task.FromResult(0);
            }));

            return graphClient;
        }

Upvotes: 1

Related Questions