Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Create and configure Microsoft Entra (Azure AD) app registrations, scopes, and service principals
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/console-app-example.md
1# Console Application Examples23This document provides complete working examples of console applications that authenticate with Microsoft Entra ID using MSAL (Microsoft Authentication Library).45## Table of Contents67- [C# (.NET) Example](#c-net-example)8- [Python Example](#python-example)9- [JavaScript (Node.js) Example](#javascript-nodejs-example)1011## C# (.NET) Example1213### Prerequisites1415```bash16dotnet new console -n EntraAuthConsole17cd EntraAuthConsole18dotnet add package Microsoft.Identity.Client19```2021### Complete Code2223```csharp24using Microsoft.Identity.Client;25using System;26using System.Linq;27using System.Threading.Tasks;2829namespace EntraAuthConsole30{31class Program32{33// Configuration - replace with your values34private const string ClientId = "YOUR_APPLICATION_CLIENT_ID";35private const string TenantId = "YOUR_TENANT_ID";36private static readonly string[] Scopes = new[] { "User.Read" };3738static async Task Main(string[] args)39{40try41{42// Build the MSAL client43var app = PublicClientApplicationBuilder44.Create(ClientId)45.WithAuthority(AzureCloudInstance.AzurePublic, TenantId)46.WithRedirectUri("http://localhost")47.Build();4849// Try to get token silently from cache first50var accounts = await app.GetAccountsAsync();51AuthenticationResult result;5253try54{55result = await app.AcquireTokenSilent(Scopes, accounts.FirstOrDefault())56.ExecuteAsync();57Console.WriteLine("Token acquired from cache");58}59catch (MsalUiRequiredException)60{61// Interactive authentication required62result = await app.AcquireTokenInteractive(Scopes)63.WithPrompt(Prompt.SelectAccount)64.ExecuteAsync();65Console.WriteLine("Token acquired interactively");66}6768// Display user information69Console.WriteLine($"\nWelcome, {result.Account.Username}!");70Console.WriteLine($"Token expires: {result.ExpiresOn}");7172// Call Microsoft Graph API73await CallGraphApiAsync(result.AccessToken);74}75catch (MsalException ex)76{77Console.WriteLine($"Error acquiring token: {ex.Message}");78}79}8081private static async Task CallGraphApiAsync(string accessToken)82{83using var httpClient = new System.Net.Http.HttpClient();84httpClient.DefaultRequestHeaders.Authorization =85new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);8687var response = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me");8889if (response.IsSuccessStatusCode)90{91var content = await response.Content.ReadAsStringAsync();92Console.WriteLine("\nUser profile from Microsoft Graph:");93Console.WriteLine(content);94}95else96{97Console.WriteLine($"API call failed: {response.StatusCode}");98}99}100}101}102```103104### Run the Application105106```bash107dotnet run108```109110### Device Code Flow (for headless scenarios)111112```csharp113// Use this for servers or devices without a browser114result = await app.AcquireTokenWithDeviceCode(Scopes, deviceCodeResult =>115{116Console.WriteLine(deviceCodeResult.Message);117return Task.CompletedTask;118}).ExecuteAsync();119```120121---122123## Python Example124125### Prerequisites126127```bash128pip install msal requests129```130131### Complete Code132133```python134import msal135import requests136import json137138# Configuration - replace with your values139CLIENT_ID = "YOUR_APPLICATION_CLIENT_ID"140TENANT_ID = "YOUR_TENANT_ID"141AUTHORITY = f"https://login.microsoftonline.com/{TENANT_ID}"142SCOPES = ["User.Read"]143144def acquire_token_interactive():145"""Acquire token using interactive flow (opens browser)"""146app = msal.PublicClientApplication(147CLIENT_ID,148authority=AUTHORITY149)150151# Try to get token from cache first152accounts = app.get_accounts()153result = None154155if accounts:156# Try silent acquisition157result = app.acquire_token_silent(SCOPES, account=accounts[0])158if result:159print("Token acquired from cache")160161if not result:162# Interactive authentication163result = app.acquire_token_interactive(164scopes=SCOPES,165prompt="select_account"166)167print("Token acquired interactively")168169return result170171def acquire_token_device_code():172"""Acquire token using device code flow (for headless scenarios)"""173app = msal.PublicClientApplication(174CLIENT_ID,175authority=AUTHORITY176)177178flow = app.initiate_device_flow(scopes=SCOPES)179180if "user_code" not in flow:181raise Exception(f"Failed to create device flow: {flow.get('error_description')}")182183# Display instructions to user184print(flow["message"])185186# Wait for user to complete authentication187result = app.acquire_token_by_device_flow(flow)188return result189190def call_graph_api(access_token):191"""Call Microsoft Graph API with access token"""192headers = {193'Authorization': f'Bearer {access_token}',194'Content-Type': 'application/json'195}196197response = requests.get(198'https://graph.microsoft.com/v1.0/me',199headers=headers200)201202if response.status_code == 200:203user_data = response.json()204print("\nUser profile from Microsoft Graph:")205print(json.dumps(user_data, indent=2))206else:207print(f"API call failed: {response.status_code}")208print(response.text)209210def main():211# Choose authentication method212print("Select authentication method:")213print("1. Interactive (opens browser)")214print("2. Device code (for headless scenarios)")215choice = input("Enter choice (1 or 2): ")216217try:218if choice == "1":219result = acquire_token_interactive()220elif choice == "2":221result = acquire_token_device_code()222else:223print("Invalid choice")224return225226if "access_token" in result:227print(f"\nWelcome, {result.get('id_token_claims', {}).get('preferred_username', 'User')}!")228print(f"Token expires in: {result.get('expires_in')} seconds")229230# Call Microsoft Graph API231call_graph_api(result["access_token"])232else:233print(f"Error acquiring token: {result.get('error')}")234print(f"Description: {result.get('error_description')}")235236except Exception as e:237print(f"Error: {e}")238239if __name__ == "__main__":240main()241```242243### Run the Application244245```bash246python console_app.py247```248249---250251## JavaScript (Node.js) Example252253### Prerequisites254255```bash256npm init -y257npm install @azure/msal-node axios258```259260### Complete Code261262```javascript263const msal = require('@azure/msal-node');264const axios = require('axios');265266// Configuration - replace with your values267const config = {268auth: {269clientId: "YOUR_APPLICATION_CLIENT_ID",270authority: "https://login.microsoftonline.com/YOUR_TENANT_ID",271}272};273274const scopes = ["User.Read"];275276// Interactive authentication (opens browser)277async function acquireTokenInteractive() {278const pca = new msal.PublicClientApplication(config);279280const authCodeUrlParameters = {281scopes: scopes,282redirectUri: "http://localhost:3000",283};284285// This opens the browser for authentication286const response = await pca.acquireTokenInteractive(authCodeUrlParameters);287return response;288}289290// Device code flow (for headless scenarios)291async function acquireTokenDeviceCode() {292const pca = new msal.PublicClientApplication(config);293294const deviceCodeRequest = {295deviceCodeCallback: (response) => {296console.log("\n" + response.message);297},298scopes: scopes,299};300301const response = await pca.acquireTokenByDeviceCode(deviceCodeRequest);302return response;303}304305// Client credentials flow (service-to-service, no user)306async function acquireTokenClientCredentials() {307const confidentialConfig = {308auth: {309clientId: "YOUR_APPLICATION_CLIENT_ID",310authority: "https://login.microsoftonline.com/YOUR_TENANT_ID",311clientSecret: "YOUR_CLIENT_SECRET", // From app registration312}313};314315const cca = new msal.ConfidentialClientApplication(confidentialConfig);316317const clientCredentialRequest = {318scopes: ["https://graph.microsoft.com/.default"],319};320321const response = await cca.acquireTokenByClientCredential(clientCredentialRequest);322return response;323}324325// Call Microsoft Graph API326async function callGraphApi(accessToken) {327const options = {328headers: {329Authorization: `Bearer ${accessToken}`330}331};332333try {334const response = await axios.get('https://graph.microsoft.com/v1.0/me', options);335console.log('\nUser profile from Microsoft Graph:');336console.log(JSON.stringify(response.data, null, 2));337} catch (error) {338console.error('API call failed:', error.response?.status, error.message);339}340}341342// Main function343async function main() {344console.log("Select authentication method:");345console.log("1. Device code flow (recommended for CLI)");346console.log("2. Client credentials (service-to-service)");347348// For demonstration, using device code flow349// In production, get user input with readline or similar350const choice = "1";351352try {353let result;354355if (choice === "1") {356result = await acquireTokenDeviceCode();357} else if (choice === "2") {358result = await acquireTokenClientCredentials();359}360361if (result.accessToken) {362console.log('\nAuthentication successful!');363console.log(`Token expires: ${new Date(result.expiresOn)}`);364365// Call Microsoft Graph API366await callGraphApi(result.accessToken);367} else {368console.error('Failed to acquire token');369}370} catch (error) {371console.error('Error:', error.message);372}373}374375main();376```377378### Run the Application379380```bash381node console_app.js382```383384## Next Steps385386- Review [oauth-flows.md](oauth-flows.md) for flow details387- See [api-permissions.md](api-permissions.md) for permission setup388- Check [troubleshooting.md](troubleshooting.md) for common issues389390## Additional Resources391392- [MSAL Libraries](https://learn.microsoft.com/entra/msal/)393