Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Microsoft Graph from console application c#

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

like image 764
Furqan Misarwala Avatar asked Jul 10 '17 14:07

Furqan Misarwala


People also ask

How do I access Microsoft graphs?

Microsoft Graph Explorer is a web-based tool that you can use to build and test requests to the Microsoft Graph API. Access Microsoft Graph Explorer at https://developer.microsoft.com/graph/graph-explorer.


2 Answers

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.

like image 172
Marc LaFleur Avatar answered Sep 28 '22 10:09

Marc LaFleur


I assume that you already have Azure AD application with granted Administrative Consent.

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.

Then you have to add two NuGet dependencies to your dotnet project

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

Microsoft.Identity.Client for authentication using Azure AD and Microsoft.Graph for executing MS Graph queries.

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["[email protected]"].Request().GetAsync()

Update 2020.01

There is a new package Microsoft.Graph.Auth that simplify auth and token management.

Let's say you want to use some Beta API this time.

<PackageReference Include="Microsoft.Graph.Auth" Version="1.0.0-preview.2" />
<PackageReference Include="Microsoft.Graph.Beta" Version="0.12.0-preview" />
var tenantId = "you-azure-tenand-id";
var clientId = "azure-ad-application-id";
var clientSecret = "unique-secret-generated-for-this-console-app";

// Configure application
var clientApplication = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithTenantId(tenantId)
    .WithClientSecret(clientSecret)
    .Build();

// Create ClientCredentialProvider that will manage auth token for you
var authenticationProvider = new ClientCredentialProvider(clientApplication);
var graphClient = new GraphServiceClient(authenticationProvider);

// Call Graph API
var user = await graphClient.Users["[email protected]"].Request().GetAsync()
like image 34
Sergey Tihon Avatar answered Sep 28 '22 09:09

Sergey Tihon