Setting the file. One moment.
Chapter 31 · Entra App Registration
Subchapter 31.5
references/console-app-example.mdMarkdown11 KBView on GitHub
This document provides complete working examples of console applications that authenticate with Microsoft Entra ID using MSAL (Microsoft Authentication Library).
dotnet new console -n EntraAuthConsole
cd EntraAuthConsole
dotnet add package Microsoft.Identity.Clientusing Microsoft.Identity.Client;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace EntraAuthConsole
{
class Program
{
// Configuration - replace with your values
private const string ClientId = "YOUR_APPLICATION_CLIENT_ID";
private const string TenantId = "YOUR_TENANT_ID";
private static readonly string[] Scopes = new[] { "User.Read" };
static async Task Main(string[] args)
{
try
{
// Build the MSAL client
var app = PublicClientApplicationBuilder
.Create(ClientId)
.WithAuthority(AzureCloudInstance.AzurePublic, TenantId)
.WithRedirectUri("http://localhost")
.Build();
// Try to get token silently from cache first
var accounts = await app.GetAccountsAsync();
AuthenticationResult result;
try
{
result = await app.AcquireTokenSilent(Scopes, accounts.FirstOrDefault())
.ExecuteAsync();
Console.WriteLine("Token acquired from cache");
}
catch (MsalUiRequiredException)
{
// Interactive authentication required
result = await app.AcquireTokenInteractive(Scopes)
.WithPrompt(Prompt.SelectAccount)
.ExecuteAsync();
Console.WriteLine("Token acquired interactively");
}
// Display user information
Console.WriteLine($"\nWelcome, {result.Account.Username}!");
Console.WriteLine($"Token expires: {result.ExpiresOn}");
// Call Microsoft Graph API
await CallGraphApiAsync(result.AccessToken);
}
catch (MsalException ex)
{
Console.WriteLine($"Error acquiring token: {ex.Message}");
}
}
private static async Task CallGraphApiAsync(string accessToken)
{
using var httpClient = new System.Net.Http.HttpClient();
httpClient.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
var response = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me");
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine("\nUser profile from Microsoft Graph:");
Console.WriteLine(content);
}
else
{
Console.WriteLine($"API call failed: {response.StatusCode}");
}
}
}
}dotnet run// Use this for servers or devices without a browser
result = await app.AcquireTokenWithDeviceCode(Scopes, deviceCodeResult =>
{
Console.WriteLine(deviceCodeResult.Message);
return Task.CompletedTask;
}).ExecuteAsync();pip install msal requestsimport msal
import requests
import json
# Configuration - replace with your values
CLIENT_ID = "YOUR_APPLICATION_CLIENT_ID"
TENANT_ID = "YOUR_TENANT_ID"
AUTHORITY = f"https://login.microsoftonline.com/{TENANT_ID}"
SCOPES = ["User.Read"]
def acquire_token_interactive():
"""Acquire token using interactive flow (opens browser)"""
app = msal.PublicClientApplication(
CLIENT_ID
python console_app.pynpm init -y
npm install @azure/msal-node axiosconst msal = require('@azure/msal-node');
const axios = require('axios');
// Configuration - replace with your values
const config = {
auth: {
clientId: "YOUR_APPLICATION_CLIENT_ID",
authority: "https://login.microsoftonline.com/YOUR_TENANT_ID",
}
};
const scopes = ["User.Read"];
// Interactive authentication (opens browser)
node console_app.js