How to call Microsoft Graph from a C # console application

I need to call the Microsoft Graph API to create a user in Azure AD.

First I need to test the console application and then run it in Azure.

https://developer.microsoft.com/en-us/graph/graph-explorer

I am new to the Microsoft Graph API how to connect and execute the API from a C # console application.

I have already registered the application in AAD.

I am trying to get a token like:

string resourceId = "https://graph.microsoft.com";
string tenantId = "<tenantID>";
string authString = "https://login.microsoftonline.com/" + tenantId;
string upn = String.Empty;
string clientId = "<ClientID>";
string clientSecret = "<clientSecret>";
//string clientSecret = ConfigurationManager.AppSettings["clientSecret"];


log.Verbose("ClientSecret=" + clientSecret);
log.Verbose("authString=" + authString);

var authenticationContext = new AuthenticationContext(authString, false);

// Config for OAuth client credentials 
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(resourceId,clientCred);
string token = authenticationResult.AccessToken;
log.Verbose("token=" + token);

I am trying to use an existing AADB2C. B2C-extension-applications. Do not change. Used by AADB2C to store user data.

I have allowed permission: enter image description here

I do not receive an exception and do not receive an access token, and the program silently exits

Also:

A new library has appeared

 <package id="Microsoft.Identity.Client" version="1.1.0-preview" targetFramework="net46" />

How can I direct login without logging in with the following and get a token? PublicClientApplication

+5
5

, . , . , " " , .

" ", , User.ReadWrite.All.

, Graph API. Graph - REST API, HTTP , .

Microsoft Graph REST. , /, , (.. ). , , PowerShell.

+7

MSAL MSAL (Microsoft Authentication Library) .NET.

Microsoft Graph, RunAsync() , GraphServiceClient:

static async Task RunAsync()
    {
        const string clientId = "your client id";
        string[] scopes = { "User.Read" };
        AuthenticationResult result;

        var clientApp = new PublicClientApplication(clientId);
        try
        {
            result = await clientApp.AcquireTokenAsync(scopes.Split(new char[] { ' ' }));
            Console.WriteLine(result.AccessToken);
            GraphServiceClient graphClient = new GraphServiceClient(
                new DelegateAuthenticationProvider(
                    async (requestMessage) =>
                    {
                        // Append the access token to the request.
                        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken);

                        // Some identifying header
                        requestMessage.Headers.Add("SampleID", "aspnet-connect-sample");
                    }));

            // Get a page of mail from the inbox
            var inboxMail = await graphClient.Me.MailFolders.Inbox.Messages.Request().GetAsync();
            foreach(var mail in inboxMail.CurrentPage.ToList())
            {
                Console.Write("From: {0}\nSubject: {1}\nBody:\n{2}\n--------------------\n", mail.From.EmailAddress.Address, mail.Subject, mail.BodyPreview);
            }
        }

        // Unable to retrieve the access token silently.
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
+1

, , , . , , :

  1. O365 ( office.com - , ). , Azure, - . Azure Portal Active Directory/properties, .
  2. https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-netcore-daemon, . ( ). .
  3. github , , .
  4. , ConfigurationBuilder, .NETCore 2.1. (, , /):

    authenticationConfig.Tenant = Configuration.GetSection("Tenant"). Value.ToString(); authenticationConfig.ClientId = Configuration.GetSection("ClientId"). Value.ToString(); authenticationConfig.ClientSecret = Configuration.GetSection("ClientSecret"). Value.ToString();

  5. . (https://developer.microsoft.com/en-us/graph/graph-explorer), URL- ( Program.cs, ). , v2.0 API - "" ( "beta", "v1.0" - -, , , ).

    await apiCaller.CallWebApiAndProcessResultASync(" https://graph.microsoft.com/v1.0/users ", result.AccessToken, Display);

0

API- Azure AD Graph Azure AD B2C. Microsoft Graph API. .

@GitHub: AzureADQuickStarts/B2C-GraphAPI-DotNet .

0

, Azure AD .

To connect from the console application, you first need to get a valid token. Since you do not have a user interface, you want to access without a user. Please note that this type of application-only token requires administrative consent before it can be used.

Then you need to add two dependencies NuGetto your projectdotnet

<PackageReference Include="Microsoft.Graph" Version="1.15.0" />
<PackageReference Include="Microsoft.Identity.Client" Version="4.0.0" />

Microsoft.Identity.Clientfor authentication using Azure AD and Microsoft.Graphfor performing MS Graph requests.

var tenantId = "you-azure-tenand-id";
var clientId = "azure-ad-application-id";
var clientSecret = "unique-secret-generated-for-this-console-app";

// Configure app builder
var authority = $"https://login.microsoftonline.com/{tenantId}";
var app = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithClientSecret(clientSecret)
    .WithAuthority(new Uri(authority))
    .Build(); 

// Acquire tokens for Graph API
var scopes = new[] {"https://graph.microsoft.com/.default"};
var authenticationResult = await app.AcquireTokenForClient(scopes).ExecuteAsync();

// Create GraphClient and attach auth header to all request (acquired on previous step)
var graphClient = new GraphServiceClient(
    new DelegateAuthenticationProvider(requestMessage => {
        requestMessage.Headers.Authorization = 
            new AuthenticationHeaderValue("bearer", authenticationResult.AccessToken);

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

// Call Graph API
var user = await graphClient.Users["Me@domain.com"].Request().GetAsync()
0
source

Source: https://habr.com/ru/post/1681117/


All Articles