Liero
Liero

Reputation: 27338

How to access Microsoft Graph's services with service-user credentials

I have created a special service account in AAD that I want to use to send email notifications to users.

In asp.net core 2 web app, how do I get access token for that service account? The samples I've seen uses user's identity, but that is not my case.

I will have probably some background process, so there cannot be any user interactivity.

Upvotes: 0

Views: 2659

Answers (1)

Bruce Chen
Bruce Chen

Reputation: 18465

I will have probably some background process, so there cannot be any user interactivity.

you could use OAuth 2 Resource Owner Password Credentials grant. Note: The resource owner password grant doesn't provide consent and doesn't support MFA either. Detailed tutorial, you could follow here. Moreover, you could use ADAL to retrieve the access_token instead of constructing the HttpClient by yourself.

The code for acquire the token via ADAL would look like:

var result = await authContext.AcquireTokenAsync("https://graph.microsoft.com","<clientId>", new UserPasswordCredential("<userName>", "<password>"));

Moreover, as juunas commented that you could use the service to service scenario and use the application permissions instead of the user delegated permissions. The code would look like this:

var result = await authContext.AcquireTokenAsync("https://graph.microsoft.com", new ClientCredential("<clientId>", "<clientSecrets>"));

For your AAD app on Azure Portal, you need to configure the required permissions for accessing Microsoft Graph API as follows:

enter image description here

Note: For Send mail Microsoft graph API, you need to set the related permission. For Resource Owner Password Credentials grant flow, you need to choose the delegated permission Send mail as a user (Mail.Send). While for client credential flow, you need to choose the application permission Send mail as any user (Mail.Send), then click grant permissions (this permission needs global admin to consent).

After retrieved the access_token, you could use Microsoft Graph Client Library for .NET to communicate with Microsoft Graph API to send the email. The initialization for GraphServiceClient would look like this:

//initialize the GraphServiceClient instance
var graphClient = new GraphServiceClient(
            "https://graph.microsoft.com/v1.0",
            new DelegateAuthenticationProvider(
                async (requestMessage) =>
                {
                    var token = await GetAccessTokenAsync();
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
                }));

Upvotes: 3

Related Questions