Skip to content

Instantly share code, notes, and snippets.

@rohit-lakhanpal
Created December 16, 2021 06:37
Show Gist options
  • Save rohit-lakhanpal/ae40a82029ac15f561791290bd397fcf to your computer and use it in GitHub Desktop.
Save rohit-lakhanpal/ae40a82029ac15f561791290bd397fcf to your computer and use it in GitHub Desktop.
Use the Microsoft.Identity.Client to acquire a token from AD for your daemon or service (using client credentials).
namespace GetToken.Console
{
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Client;
using Microsoft.Identity.Web;
using System;
using System.Globalization;
public class Program
{
public static async Task Main()
{
/*
* /appsettings.json
* {
* "Instance": "https://login.microsoftonline.com/{0}",
* "ApiUrl": "[Enter app url eg. https://graph.microsoft.com/ or https://management.azure.com/ or https://my-app.eastus.kusto.windows.net/]",
* "Tenant": "[Enter here the tenantID or domain name for your Azure AD tenant]",
* "ClientId": "[Enter here the ClientId for your application]",
* "ClientSecret": "[Enter here a client secret for your application]"
* }
*/
AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");
IConfidentialClientApplication app;
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
.WithClientSecret(config.ClientSecret)
.WithAuthority(new Uri(config.Authority))
.Build();
app.AddInMemoryTokenCache();
string[] scopes = new string[] { $"{config.ApiUrl}.default" };
AuthenticationResult result = null;
try
{
result = await app.AcquireTokenForClient(scopes)
.ExecuteAsync();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Token acquired");
Console.ResetColor();
}
catch (MsalServiceException ex) when (ex.Message.Contains("AADSTS70011"))
{
// Invalid scope. The scope has to be of the form "https://resourceurl/.default"
// Mitigation: change the scope to be as expected
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Scope provided is not supported");
Console.ResetColor();
}
if (result != null)
{
Console.WriteLine($"Access Token: \n{result.AccessToken}");
}
}
}
public class AuthenticationConfig
{
public string Instance { get; set; } = "https://login.microsoftonline.com/{0}";
public string ApiUrl { get; set; } = "https://graph.microsoft.com/";
public string Tenant { get; set; }
public string ClientId { get; set; }
public string Authority
{
get
{
return String.Format(CultureInfo.InvariantCulture, Instance, Tenant);
}
}
public string ClientSecret { get; set; }
public string CertificateName { get; set; }
public static AuthenticationConfig ReadFromJsonFile(string path)
{
IConfigurationRoot Configuration;
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path);
Configuration = builder.Build();
return Configuration.Get<AuthenticationConfig>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment