Code sample 1:

Below is example code for authenticating using the Microsoft.Identity.Client-nuget in C#, however libraries for most languages exist for authenticating, list here. Note: It is recommended to use the latest version of required libraries.


    var setup = new {
        AuthUrl = authUrl, // Provided to you by EG, in the form of https://login.microsoftonline.com/mytenant.onmicrosoft.com
        ClientId = clientId, // Provided to you by EG, in the form of a GUID
        X509Certificate = GetFromCertificateStore(), // Created by you, and the public key part is sent to EG. Remember to keep the private key secret.
        ServiceUrl = "http://someservice.egretail-test.cloud/something", // Can be found on our main documentation page
        ServiceResourceId = "some-other-guid" // Can be found on our main documentation page
    };

    // Cache authContext until the certificate expires, auto-rollover to a new certificates is recommended
    var authContext = ConfidentialClientApplicationBuilder.Create(setup.ClientId)
                    .WithAuthority(setup.AuthUrl)
                    .WithCertificate(setup.X509Certificate)
                    .Build();

    // There are more correct ways of doing this, but this most clearly illustrates the concept
    var scopes = new[] { $"{setup.ServiceResourceId}/.default" };
    var authResult = await authContext.AcquireTokenForClient(scopes).ExecuteAsync();
    var httpClient = new HttpClient();
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

    // Call the actual service with an access_token
    var responseMessage = await httpClient.GetAsync(setup.ServiceUrl);

Code sample 2:

Below is example code for getting certificates from a Windows Certificate store using C#, other OSes/languages do this differently. This code enables certificate rotation by always getting the newest certificate.

public static X509Certificate2 GetFromCertificateStore(string commonName)
{
    using (var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
    {
        certStore.Open(OpenFlags.ReadOnly);
        var certs = certStore.Certificates.Find(X509FindType.FindBySubjectName, $"{commonName}", false).OfType<X509Certificate2>()
                    .Where(c => c.SubjectName.Name?.Contains($"CN={commonName}") ?? false) // Make sure it is actually the CN
                    .ToArray();
        certStore.Close();

        if (certs.Length == 0) throw new Exception($"Cert '{commonName}' not found");

        // Return the newest certificate, enables certificate rotation.
        return certs.OrderByDescending(c => c.NotAfter).First();
    }
}