Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 14 · Lesson 131 · 7 min read

Machine-to-Machine Auth: Client Credentials Flow

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: Managed Identity in Code, App-Role Authorization and a Federated Pipeline
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Choose the right authentication for services and jobs that act without a user, use managed identity and workload identity federation to remove stored secrets, validate app-only tokens correctly in an API, and apply least privilege and sender-constrained tokens where risk justifies them.

Concept Explanation

Most of this course has been about users signing in. But a great deal of traffic has no user: a nightly job calling the API, a reporting service reading from the tasks service, a build pipeline deploying to Azure, an integration pushing data from a partner. Each needs an identity, and how that identity proves itself is where many breaches begin, because the easy answer is a long-lived secret pasted into configuration. The OAuth 2.0 client credentials flow is the standard mechanism: the calling application authenticates to the identity provider with its own credential and receives an access token for a specific audience, containing app roles or scopes that describe what it may do. The API validates that token like any other, checking the signature, issuer, audience, and expiry, and then authorizes based on the roles it carries.

The strength of the caller's credential is the weak point, and there is a ladder from worst to best. A client secret is a password for an application: it leaks through repositories, logs, and screenshots, and it expires and must be rotated. A certificate is stronger, since the private key can be kept in a vault or hardware and never transmitted. Best of all is having no stored credential. Managed identity gives an Azure resource, such as a Container App or Function, an identity that the platform authenticates automatically, so code obtains a token with no secret at all. Workload identity federation extends this beyond Azure: a system with its own trusted identity, such as a GitHub Actions run or a Kubernetes service account, presents a short-lived token from its own issuer, and the identity provider is configured to trust it for a specific repository or namespace and exchange it for a token. Day 83 used this for deployments, and the same idea applies between any workloads.

On the receiving side, an API must be able to tell an app token from a user token, since the checks differ. App-only tokens carry app roles and no delegated scopes or user identifier, and an endpoint that should be reachable only by a service must require the specific app role, not merely a valid token, otherwise any application in the tenant that can obtain a token for the audience could call it. Conversely, an endpoint meant for users should reject tokens that have no user. Grant each caller the narrowest role, review the permissions of service principals regularly, since they tend to accumulate, and prefer roles specific to your API over broad directory permissions.

Bearer tokens can be stolen and replayed by whoever holds them. Sender-constrained tokens bind a token to a key that only the legitimate client holds. Mutual TLS-bound tokens, defined in RFC 8705, tie the token to the client certificate, and DPoP, in RFC 9449, has the client sign each request with a private key. They are worth using for high-value APIs and partner integrations. Keep token lifetimes short, cache tokens until near expiry to avoid needless requests to the identity provider, and treat signing keys as crown jewels: the 2023 Storm-0558 incident, in which a stolen signing key was used to forge tokens, shows that an attacker who can mint tokens bypasses every other control.

CredentialRiskWhen to use
Client secretLeaks easily, must be rotatedOnly for low-risk cases and local development
CertificatePrivate key can be protected in a vault or hardwareWhen federation is unavailable
Managed identityNo secret exists, platform authenticatesAzure workloads calling Azure or Entra-protected APIs
Workload identity federationShort-lived token from a trusted issuerCI pipelines, Kubernetes, other clouds
Sender-constrained tokens (mTLS, DPoP)Stolen tokens cannot be replayedHigh-value APIs and partner integrations
API keysBearer secret, no standard expirySimple external integrations, see Day 127

Worked Example: Managed Identity in Code, App-Role Authorization and a Federated Pipeline

The caller obtains tokens without a secret, the API requires an app role, and the Bicep grants a federated credential.

C#
// Caller: no secret anywhere. In Azure this uses the managed identity, locally it falls back to the developer's sign-in.
var credential = new DefaultAzureCredential();
builder.Services.AddHttpClient("reporting", c => c.BaseAddress = new Uri("https://api.example.com/"))
    .AddHttpMessageHandler(() => new BearerTokenHandler(credential, scope: "api://tasks-api/.default"));

public sealed class BearerTokenHandler(TokenCredential credential, string scope) : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
    {
        var token = await credential.GetTokenAsync(new TokenRequestContext([scope]), ct);     // the SDK caches until near expiry
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.Token);
        return await base.SendAsync(request, ct);
    }
}

// Where a certificate is unavoidable: the private key lives in Key Vault or the certificate store, never in the repository.
var app = ConfidentialClientApplicationBuilder.Create(clientId).WithAuthority($"https://login.microsoftonline.com/{tenantId}")
    .WithCertificate(certificate).Build();
var result = await app.AcquireTokenForClient(["api://tasks-api/.default"]).ExecuteAsync(ct);
C#
// API: distinguish app tokens from user tokens, and require the specific app role for service endpoints.
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("ReportsReader", p => p.RequireAuthenticatedUser()
        .RequireClaim("roles", "Reports.Read")                                       // an app role assigned to the calling service
        .RequireAssertion(ctx => ctx.User.FindFirst("scp") is null))                  // no delegated scope: this is an app token, not a user
    .AddPolicy("UserOnly", p => p.RequireAssertion(ctx => ctx.User.FindFirst("oid") is not null && ctx.User.FindFirst("roles") is null));

app.MapGet("/internal/reports/summary", (ClaimsPrincipal caller) =>
{
    var appId = caller.FindFirstValue("azp") ?? caller.FindFirstValue("appid");     // which application is calling, for audit
    return Results.Ok(new { calledBy = appId });
}).RequireAuthorization("ReportsReader");

// Token validation stays strict: issuer, audience and lifetime, with a small clock skew.
builder.Services.AddAuthentication().AddJwtBearer(o =>
{
    o.Authority = $"https://login.microsoftonline.com/{tenantId}/v2.0";
    o.TokenValidationParameters = new() { ValidAudience = "api://tasks-api", ValidateIssuer = true, ValidateLifetime = true, ClockSkew = TimeSpan.FromMinutes(1) };
});
Bicep
// Workload identity federation: a specific GitHub repository and branch may obtain tokens as this identity. No secret is stored.
resource identity 'Microsoft.ManagedIdentity/userAssignedIdentities@2023-01-31' existing = { name: 'id-deploy' }
resource fic 'Microsoft.ManagedIdentity/userAssignedIdentities/federatedIdentityCredentials@2023-01-31' = {
  parent: identity
  name: 'github-main'
  properties: {
    issuer: 'https://token.actions.githubusercontent.com'
    subject: 'repo:acme/taskboard:ref:refs/heads/main'          // exact repository and branch, not a wildcard
    audiences: ['api://AzureADTokenExchange']
  }
}
Code
Service identity review, quarterly
  List every service principal and managed identity, its owner, and its assigned roles.
  Remove unused ones and any role broader than the calls actually made.
  Confirm no client secret is older than 90 days, then replace remaining secrets with certificates or federation.
  Alert on token requests from unexpected locations or for unexpected audiences.

The subject in the federated credential is the security boundary. A wildcard there would let any branch or pull request in the repository act as the identity, so pin it to the exact ref or to an environment protected by approvals.

A client secret is a password for an application and leaks easily. A certificate keeps the private key in a vault. Managed identity and workload identity federation remove stored credentials entirely. The API requires a specific app role and tells app tokens from user tokens.
A client secret is a password for an application and leaks easily. A certificate keeps the private key in a vault. Managed identity and workload identity federation remove stored credentials entirely. The API requires a specific app role and tells app tokens from user tokens.

Real-World Examples

  • In 2016 attackers found Amazon Web Services credentials in a private Uber code repository on GitHub, used them to access data of about 57 million users and drivers, and the company was later found to have concealed the incident. It became a standard case for keeping secrets out of source control and for using short-lived, scoped credentials rather than long-lived keys.
  • In July 2023 Microsoft reported that an actor tracked as Storm-0558 had used an acquired consumer signing key to forge authentication tokens and access email at about two dozen organizations, and a later review criticized the company's key handling. The incident showed that protecting token signing keys and validating that tokens come from the right issuer for the right audience are central to any identity design.
Key TakeawaysService-to-service calls need real identities of their own, using the OAuth client credentials flow rather than shared passwords. Prefer managed identity or workload identity federation over secrets, and certificates over passwords. The API must validate issuer and audience, tell app tokens from user tokens, and require specific app roles, and callers should get least privilege reviewed regularly, with sender-constrained tokens for high-value APIs.

Review Questions & Answers

With a managed identity there is no secret to store, leak, or rotate, because the platform authenticates the resource and issues tokens on request. A client secret can be leaked through code, logs, or configuration, and it expires and needs manual rotation.

It lets the pipeline present a short-lived token from its own trusted issuer, such as GitHub, which the identity provider exchanges for an access token for a specific identity. No stored credential exists, and the trust is restricted to a named repository and branch.

Any application that can get a token for the audience would otherwise be able to call the endpoint. Requiring an app role that you assigned only to the intended services makes the permission explicit and auditable.

The token is bound to a key held by the client, and each request must be signed with it, so a stolen token cannot be used without the private key. This limits replay by an attacker who captured only the bearer token.