Skip to content
Bogdan Gavril edited this page Oct 25, 2023 · 13 revisions

Which SDK to use?

SDK MSI CAE support MSI TB support FIC CAE FIC TB Ease of use
MSAL Y N Y N Hard
ID.Web N N Y N Easy
Azure.Identity N N N N ?

When to use each SDK?

We recommend using higher level SDKs like Microsoft.Identity.Web and Azure.Identity; Applications needing full control (e.g. other SDKs) can use MSAL directly.

MSAL experience


## MSI CAE + TB

```csharp

public async AuthenticationResult GetMsiTokenAsync(string resource, string claims )
{
    ManagedIdentityApplication mia = ManagedIdentityApplication
                                         .Create(ManagedIdentityType.SystemAssigned)
                                         .WithClientCapabilities(new[] {"cp1"} );

    // if claims are not null, cache is bypassed and a new token is acquired.
    var authResult = await mia.AcquireToken(resource)
                              .WithClaims(claims) 
                              .TryMtlsProofOfPosession() // if resource doesn't support it, we'll still get a Bearer
                              .ExecuteAsync();

    return authResult;
}


public async HttpResponse CallProtectedApiAsync(AuthenticationResult ar, HttpRequest request)
{
    request.Headers.Authorization.Add(ar.GetAuthorizationHeader());
    var httpClient = GetHttpClient(ar.MtlsCertificate);
    HttpResponse response = await s_httpClient.SendAsync(request);

    if (response.StatusCode == 401)
    { 
        string claims = ParseClaimsChallenge(response);
        if (claims != null) 
        {
            AuthenticationResult arWithClaims = GetMsiTokenAsync(claims);
            return CallProtectedApi(arWithClaims);  // TODO: break the recursion loop after 1-2 attempts
        }
    }
 
    return response;
    
}

string ParseClaimsChallenge(HttpResponse response)
{
    var params = WWWAuthenticeHeaders.Parse(response);
    return params.Claims;
}

private static ConcurrentDictionary<string, HttpClient> s_httpClients = 
   new ConcurrentDictionary<string, HttpClient>();

public static HttpClient GetHttpClient(X509Certificate2 certificate)
{
   if (certificate=null) { 
      return s_httpClients.GetOrAdd("non_mtls", (cert) => return new HttpClient());
   }
   
    return s_httpClients.GetOrAdd(cert.Thumbprint, (cert) => return new HttpClient() { ClientCertificate = cert);
   
}

// ORCHESTRATION LOGIC

var ar = await GetMsiTokenAsync("https://arm.management.com/.default", claims: null);
HttpRequest request = new HttpRequest("https://arm.management.com/list_stuff");
HttpResponse response = await CallProtectedApiAsync(ar, request);


FIC + CAE + TB

// Leg1 - get MSI token var ar = await GetMsiTokenAsync("https://arm.management.com/.default");

Getting started with MSAL.NET

Acquiring tokens

Web Apps / Web APIs / daemon apps

Desktop/Mobile apps

Advanced topics

FAQ

Other resources

Clone this wiki locally