Get my user's information using MS Graph API

I'm trying to get my information using the Graph API SDK for C# (the idea is the application running without user interaction), as shows code sample below:

IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
    .Create("xxx")
    .WithTenantId("xxx")
    .WithClientSecret("xxx")
    .Build();

ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);


GraphServiceClient graphClient = new GraphServiceClient(authProvider);

var user = await graphClient.Me.Request()
    .Select(u => new
    {
        u.DisplayName,
        u.Mail,
        u.UserPrincipalName
    })
    .GetAsync();

It's returning 'WaitingForActivation' on Status, I don't know where is the problem.

Upvotes: 3

Views: 4436

Answers (1)

Carl Zhao
Carl Zhao

Reputation: 9511

This is not like you think. If you call the /me endpoint, you must log in the user. It actually obtains the logged-in user information, so you cannot use the client credential flow to obtain the access token. For the client credential flow, it is usually used for server-to-server interactions that must run in the background and do not interact with the user immediately(No user logged in). For the /me endpoint, it needs to accept the user token, because it has user interaction. So, I suggest you use auth code flow to get access token,which requires you to log in to the user and obtain the authorization code, and then use the authorization code to redeem the access token.

Authorization code provider:

IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithRedirectUri(redirectUri)
    .WithClientSecret(clientSecret) // or .WithCertificate(certificate)
    .Build();

AuthorizationCodeProvider authProvider = new AuthorizationCodeProvider(confidentialClientApplication, scopes);

By the way, if you want to get user information in a scenario where no user is logged in, you can call the /users endpoint:

IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
    .Create("xxx")
    .WithTenantId("xxx")
    .WithClientSecret("xxx")
    .Build();

ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);


GraphServiceClient graphClient = new GraphServiceClient(authProvider);

var user = await graphClient.Users["{userId or userPrincipalName}"].Request()
    .Select(u => new
    {
        u.DisplayName,
        u.Mail,
        u.UserPrincipalName
    })
    .GetAsync();

Upvotes: 1

Related Questions