Skip to content

Instantly share code, notes, and snippets.

@ahelland
Last active December 11, 2018 07:15
Show Gist options
  • Save ahelland/cbc8530c21d6684adfd4587b28d915ba to your computer and use it in GitHub Desktop.
Save ahelland/cbc8530c21d6684adfd4587b28d915ba to your computer and use it in GitHub Desktop.
Acquiring token using client certificate
using System;
using System.Security.Cryptography.X509Certificates;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
namespace SignedJwt
{
class Program
{
static void Main(string[] args)
{
string adfsInstance = "https://contoso.com/adfs/";
string ResourceId = "https://contoso.com/api";
string clientId = "copy-from-adfs-server";
string clientSecret = "copy-from-adfs-server";
ClientAssertionCertificate certCred = null;
AuthenticationContext authContext = null;
var authority = $"{adfsInstance}";
authContext = new AuthenticationContext(authority, false);
X509Certificate2 cert = new X509Certificate2("adfs.contoso.com.pfx");
var token = "";
AuthenticationResult result = null;
try
{
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
certCred = new ClientAssertionCertificate(clientId, cert);
result = authContext.AcquireTokenAsync(ResourceId, certCred).Result;
token = result.AccessToken;
}
catch (Exception x)
{
Console.WriteLine($"Error: {x.Message}");
}
Console.WriteLine($"Token: {token}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment