How to call Microsoft Graph from console application c#

Furqan Misarwala picture Furqan Misarwala · Jul 10, 2017 · Viewed 12.1k times · Source

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

First I need to test from console application and then need to implement in Azure function.

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

I am new to Microsoft Graph API , How can I connect and execute API from c# console application.

I have already registered the application in AAD.

I am trying to acquire token as :

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 trying to use existing AADB2C. b2c-extensions-app. Do not modify. Used by AADB2C for storing user data.

I have enabled permission as: enter image description here

I neither get exception nor get access token and program silently exit

Also :

There is new library

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

How can I direct login without login pop-up with the following and acquire token ? PublicClientApplication

Answer

Marc LaFleur picture Marc LaFleur · Jul 10, 2017

In order to connect from a console app, you'll need to first obtain a valid token. Since you lack a UI, you'll want to Get access without a user. Note that this type of "app-only" token requires Administrative Consent before it can be used.

In order to support the Create User scenario, you will need to ensure your permission scopes include User.ReadWrite.All.

Once you have a valid token you can make calls into the Graph API. Graph is a REST API so all calls are made over HTTP with the token passed within the Authorization Header.

You can read a general overview at Get started with Microsoft Graph and REST. There are also several language/framework specific overviews available but all of them assume you have a UI (i.e. not simply console). Generally speaking, if you're looking for a console tool for creating users you may prefer using PowerShell.