I have an ASP.NET Core application and I am trying to get the access token from AAD using a certificate. I am using Microsoft.IdentityModel.Clients.ActiveDirectory
assembly of version 3.13.5.907. But it seems that the ClientAssertionCertificate
class has been removed from this assembly. The interface IClientAssertionCertificate
is available but I can't find any class that is imlpementing it.
In ASP.NET 4.5 I used to use the following code for getting access token from AAD using certificates (Microsoft.IdentityModel.Clients.ActiveDirectory
assembly of version 3.13.4.878)
var clientCredential = new ClientAssertionCertificate(_appId, _thumbprint);
var authenticationContext = new AuthenticationContext(authority, false);
var result = await authenticationContext.AcquireTokenAsync(resource, clientCredential);
Has this class been depreciated in ASP.NET Core or am I missing something?
I had the same issue today; turns out it is pretty easy to write your own concrete implementation of IClientAssertionCertificate
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.IdentityModel.Tokens;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace app{
internal class ClientAssertionCertificate : IClientAssertionCertificate {
private X509Certificate2 certificate;
public string ClientId { get; private set; }
public string Thumbprint {
get {
return Base64UrlEncoder.Encode(certificate.GetCertHash());
}
}
public ClientAssertionCertificate(string clientId, X509Certificate2 certificate) {
ClientId = clientId;
this.certificate = certificate;
}
public byte[] Sign(string message) {
using (var key = certificate.GetRSAPrivateKey()) {
return key.SignData(Encoding.UTF8.GetBytes(message), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
}
}
}
In addition to referencing package Microsoft.IdentityModel.Clients.ActiveDirectory, you'll also need to add the package Microsoft.IdentityModel.Tokens (for the Base64UrlEncoder)
Source: https://blog.mastykarz.nl/azure-ad-app-only-access-token-using-certificate-dotnet-core/
Just an update to anyone seeing this post now. This is now available in the latest .NETStandard 2.0 version.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With