C# / .NET Compendium PLEN
.NET / C# / Security

API for companies: Client Credentials, API keys and OpenIddict

The scenario

You are building an API that exposes a price list to companies (business customers). The client is another company's server, not a person in a browser. It gets a long secret by which you recognise its account and permissions (e.g. a role or a scope: read the price list, write). The requirements: HTTPS, access control, abuse detection, and ideally also a refresh token with its hash in the database.

This is machine-to-machine communication. In OAuth2 it corresponds to the Client Credentials flow, in which client_id + client_secret replace a person's login and password.

Three ways

Way When Notes
A. An API key in a header (no JWT) few customers, a simple price list On every request you look up the key's hash in the database (with a cache), the role from the database. Revoking a key works immediately. The fewest moving parts.
B. Your own /token endpoint: a key -> a short JWT you want a JWT and full control Reasonable in a small, closed case, but it is not "OAuth2" and you are responsible for the security yourself.
C. An OAuth2-compliant server: a ready-made product (Keycloak, Entra ID, Auth0) or a framework to build one (OpenIddict) customers are to use standard libraries, several kinds of access, growing scale Real OAuth2 client_credentials, clients and secrets in the database, rotation, audit. More configuration at the start.

You always do JWT validation with a library (JwtBearer), whichever way you choose. Your own token server is for learning; in production a ready-made one is better.

How Client Credentials works

Klient                          Serwer autoryzacji              API z cennikiem
  | POST /connect/token  ----------> |                               |
  |  client_id + client_secret       | sprawdza sekret (hash w bazie)|
  |  scope=pricing:read              | sprawdza dozwolone zakresy    |
  | <---------- access_token (JWT, 10 min)                           |
  | GET /api/prices  (Authorization: Bearer ...) ------------------> |
  |                                                  checks the signature, validity, scope
  | <---------------------------------------------------- 200 + dane |

There is no user logging in here. The token represents the client itself, and what it can do follows from the scopes granted to it in the database.

What this gives the client (way C)

  • Standard libraries in every language. The client configures a ready-made OAuth2 client (the token address, client_id, client_secret, the scope) and the library fetches and renews the token itself. It doesn't write code for your custom mechanism.
  • A known flow, so shorter onboarding and less documentation of your own.
  • Scopes: the token says what the client has access to (pricing:read, pricing:write).
  • Predictable errors (invalid_client, invalid_scope) and an expires_in field in the response.
  • Separating the identifier from the secret, easier secret rotation and disabling one client without affecting the others.
  • For you: you don't maintain your own token-issuing code and signing-key rotation, and as the product grows it is easy to add other flows (people logging in, SSO).

Does a refresh token make sense here?

In Client Credentials usually not. The specification recommends not issuing a refresh token in this flow: the client holds a long-lived secret and simply asks for a new access token when the previous one expires. That is why the access token should live briefly (5-15 minutes). Rotation and reuse detection protect refresh tokens, but they don't protect the client's secret, which still lets a new token be issued. If the requirement for a refresh token is non-negotiable, the pattern from the topic Refresh token (a hash in the database, rotation, a token family, reuse detection) can be plugged into the key-exchange endpoint, but it doesn't increase the protection of the key.

What really secures such an API

  • Treat the secret like a password: random (e.g. 32 bytes from RandomNumberGenerator), in the database only a hash, shown to the client once, with an explicit prefix for identification (e.g. pk_ab12...). OpenIddict hashes client secrets itself.
  • Life cycle: an expiry date, revocation, rotation (two active secrets for the duration of the swap), LastUsedAt.
  • The secret only in a header or the request body, never in the URL (it ends up in logs).
  • HTTPS enforced: HSTS and rejecting HTTP at the edge. A secret sent over HTTP has already leaked, so a redirect alone isn't enough.
  • The role or scope in the token is frozen until the token expires. Keep the access token short or (in way A) check permissions in the database on every request.
  • A request limit per client and monitoring: with a price list the real risk is mass downloading of data, not just token theft.
  • Optionally a list of the client's allowed IP addresses.

A key on every request (A) versus a token (C)

Way A. The client sends the key in every request, and the API verifies it every time:

Klient: GET /api/prices
        X-Api-Key: pk_ab12...tajny-ciag

API (on EVERY request):
  1. the authentication handler reads the X-Api-Key header
  2. computes the key's hash (SHA-256) and looks it up in the database (usually with a short cache)
  3. missing / disabled / expired  ->  401
  4. jest  ->  buduje ClaimsPrincipal z danych z bazy (id klienta, rola, zakresy)
  5. autoryzacja (polityki, [Authorize]) sprawdza claimy  ->  200 albo 403

It is worth separating two stages: authentication (who are you?) is done by the key handler, which creates an identity with claims, and authorization (what are you allowed to do?) is done by the standard ASP.NET Core mechanism based on the claims, e.g. RequireAuthorization("pricing:read"). The endpoint doesn't know whether the identity came from a key or from a token. In the database you compare the key's hash, never the key itself.

Way C. The secret goes only to the token server, and afterwards the client uses a short-lived token:

Klient: POST /connect/token   (client_id + client_secret)    <- sekret tylko tutaj
Serwer: sprawdza sekret, wydaje access_token (JWT, 10 min) z claimami

Klient: GET /api/prices
        Authorization: Bearer <access_token>                   <- the secret is no longer sent

API:    checks the JWT's signature and validity (no database query), the claims are in the token
A: a key on every request C: a token
What travels over the network the secret key every time the secret rarely, the token often
A database query on every request (or a cache) only when issuing the token
Revoking access immediately after the token expires
Changing the client's role straight away after the token expires
Consequences of a leak the key works until revoked a stolen token works for a few minutes, but the secret still lets a new one be issued

Way A is simpler and gives immediate control, at the cost of sending the secret more often and loading the database. Way C limits the exposure of the secret and relieves the database, at the cost of a delay in revocations.

B versus C: why not to call your own endpoint OAuth2

In both ways the client exchanges a secret for a short JWT. The difference is compliance with the standard and who is responsible for the details.

  • B (your own /token): you decide everything yourself: the key in the X-Api-Key header, any shape of response, your own errors, your own signing and key rotation. Customers have to read your documentation and write code for you.
  • C (an OAuth2-compliant server): behaves as RFC 6749 (Client Credentials) describes: a POST request in application/x-www-form-urlencoded with grant_type, client_id, client_secret, scope; a JSON response with access_token, token_type, expires_in; standard errors (invalid_client, invalid_scope); discovery, JWKS, optionally revocation and introspection.

The name "OAuth2" is a promise of compliance: the client assumes a standard library will work, that edge cases are handled, and that the protocol has been analysed for security. A custom endpoint that departs from the standard will fail in non-obvious ways, and the name suggests guarantees it doesn't give.

If you replicated the endpoint from the RFC exactly, technically you would have a minimal OAuth2 server for one flow. The problem is that "exactly" means dozens of details: error codes, not revealing the existence of a client, timing-attack-resistant comparisons, secret storage, signing-key rotation, discovery. A library such as OpenIddict does precisely that, so C is in practice "B done and maintained by someone who knows what they're doing". Way B is the weakest compromise: the cost of your own token server without the benefits of the standard.

OAuth2, JWT and OpenID Connect: what is what

OAuth2 describes the flow (who exchanges what, and how, for a token), but doesn't specify the token format. JWT is the format servers most often choose for the access token (there is even a profile, RFC 9068). You can have OAuth2 without JWT (opaque tokens) and JWT without OAuth2 (your own endpoint from way B).

Token Format
Access token a JWT (self-contained, signed) or an opaque token (a random string that the API checks with the server). Both are OAuth2-compliant.
ID token (OpenID Connect) always a JWT, because the OIDC specification requires it
Refresh token usually opaque, kept in the database
  • JWT (self-contained): the API verifies the signature with the public key from the JWKS and reads the claims from the token, without asking the server or the database. Fast and scalable, but revocation works only after expiry (hence the short life).
  • Opaque (reference): the API asks the server ("introspection") or the database whether the token is valid. Revocation works immediately, at the cost of a query on every request.

OpenID Connect (OIDC) is a layer on top of OAuth2 that adds the user's identity (the ID token). It isn't a single "product API", but a set of standard HTTP endpoints:

Endpoint What it is for
/.well-known/openid-configuration discovery: JSON with the addresses of the other endpoints, the client configures itself with a single address
/connect/authorize the start of the user's login (Authorization Code + PKCE)
/connect/token exchanging a code, a refresh token or a client secret for tokens
/connect/userinfo the logged-in user's data, called with the access token
JWKS public keys for verifying the tokens' signatures
/connect/logout logging out
/connect/introspect, /connect/revoke checking and revoking a token (the OAuth2 RFCs)

The paths depend on the server, which is why the client reads them from the discovery document. In Client Credentials there is no user, so you don't use the ID token and userinfo; discovery, token and JWKS are useful. OIDC starts to matter with a panel where people log in, or with SSO. The old "OpenID 2.0" is a different, obsolete protocol.

OpenIddict: a framework, not a ready-made product

OpenIddict is a set of libraries for building your own server of OAuth 2.0 / OIDC in ASP.NET Core, not a program to run and configure in a panel.

  • It does for you: the protocol and endpoints, request validation, checking secrets (hashes), scopes and permissions, signing tokens, errors compliant with the specification, a store of clients and tokens (EF Core), managers (IOpenIddictApplicationManager) and a token validation module in the API.
  • You add yourself: a client management panel, the login screen and user accounts (if any), the decision of what goes into the token, hosting, the database, keys and certificates, rotation, audit and monitoring.
Solution Type
OpenIddict a framework: you build the server from building blocks, full control, the most work
Duende IdentityServer a framework (commercial), a similar way of working
Keycloak a ready-made product with an admin panel and an Admin REST API
Entra ID, Auth0 a cloud service, you host nothing

Refresh tokens in OpenIddict. They are supported only in flows with a user (Authorization Code); in Client Credentials there are none. The library gives rotation, reuse detection (as far as I know it revokes the whole authorization chain), a store in the database and optionally reference tokens (only the hash in the database). That is the equivalent of what was done by hand in Refresh token. A sketch (check the names in the documentation of the version you use):

.AddServer(o =>
{{
    o.AllowAuthorizationCodeFlow().RequireProofKeyForCodeExchange();
    o.AllowRefreshTokenFlow();
    o.RegisterScopes(Scopes.OfflineAccess, "pricing:read"); // the client asks for offline_access to get a refresh token
    o.SetRefreshTokenLifetime(TimeSpan.FromDays(7));
    o.SetRefreshTokenReuseLeeway(TimeSpan.FromSeconds(30)); // tolerance for parallel refreshes
    o.UseReferenceRefreshTokens();                          // optional: only a hash lives in the database
}});

Two ways of authenticating in one API

ASP.NET Core lets you register several authentication schemes and choose them per endpoint or combine them into one. It makes sense e.g. in a migration: old clients stay on keys, new ones use OAuth2, and you phase out the keys gradually. A sketch (not compiled, check the names in the documentation on multiple schemes):

// Variant 1: separate schemes, chosen per endpoint
builder.Services.AddAuthentication()
    .AddScheme<AuthenticationSchemeOptions, ApiKeyHandler>("ApiKey", null)
    .AddJwtBearer("Bearer", o => {{ /* Authority = address of the OAuth2 server */ }});

app.MapGet("/api/prices", ...)
   .RequireAuthorization(new AuthorizeAttribute {{ AuthenticationSchemes = "ApiKey,Bearer" }});

// Variant 2: one "policy scheme" that picks the handler from the request
builder.Services.AddAuthentication("Smart")
    .AddPolicyScheme("Smart", null, o =>
        o.ForwardDefaultSelector = ctx => ctx.Request.Headers.ContainsKey("X-Api-Key") ? "ApiKey" : "Bearer")
    .AddScheme<AuthenticationSchemeOptions, ApiKeyHandler>("ApiKey", null)
    .AddJwtBearer("Bearer", o => {{ }});

For this to make sense: both schemes must give the same permission model (the key handler builds a ClaimsPrincipal with the same scopes as the token, and then the policies work unchanged), and partition the request limit by the same client identifier, so that it can't be bypassed by alternating between the two ways. For a single client there is no reason to keep two paths, because the attack surface and the code to maintain grow.

Managing clients from your own panel

The OAuth2 and OIDC standards don't specify an API for managing clients (apart from the rarely deployed Dynamic Client Registration, RFC 7591). Every server has its own solution:

Server Credential management
OpenIddict no ready-made REST API; you use IOpenIddictApplicationManager in your own code and expose your own endpoints or do it in the panel
Keycloak a ready-made Admin REST API (clients, secret regeneration, roles)
Microsoft Entra ID Microsoft Graph (applications, adding and removing secrets)
Auth0 the Management API (clients, grants, secrets)
Duende IdentityServer configuration in the database (EF); the API for registering clients depends on the edition, check the licence

A sketch of the operations in OpenIddict (not compiled):

// POST /admin/clients -> creates a client, returns the secret ONCE
app.MapPost("/admin/clients", async (CreateClientRequest req, IOpenIddictApplicationManager apps) =>
{{
    var secret = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32));
    var descriptor = new OpenIddictApplicationDescriptor
    {{
        ClientId = req.ClientId, ClientSecret = secret, DisplayName = req.Name,
        ClientType = ClientTypes.Confidential,
        Permissions = {{ Permissions.Endpoints.Token, Permissions.GrantTypes.ClientCredentials }}
    }};
    foreach (var s in req.Scopes) descriptor.Permissions.Add(Permissions.Prefixes.Scope + s);
    await apps.CreateAsync(descriptor);
    return Results.Ok(new {{ req.ClientId, clientSecret = secret }}); // the only time the secret is visible
}}).RequireAuthorization("panel-admin");

Analogously: listing clients, changing scopes, rotating the secret, disabling and deleting. What to watch out for:

  • The administrative endpoints are the most sensitive part of the system: separate authentication of administrators (best through OIDC), the panel-admin role, and not the same token as for API clients; best a separate host or a path unavailable from the internet.
  • Audit: who changed what and when; don't log secrets.
  • Rotation without a break: as far as I know, OpenIddict holds one secret per application, so a smooth swap requires two client registrations or your own logic.
  • Revoking a client doesn't delete the tokens already issued, which live until they expire.

Why API providers choose an API key

Anthropic, OpenAI, Stripe or SendGrid expose their APIs mainly through an API key (this is my interpretation, not their rationale):

  • Simplicity of entry: one header and curl works in a minute, with no fetching and renewing of a token.
  • The client is the developer's server: there is no person clicking "allow", so browser flows don't fit.
  • Billing and limits per key: the key is a natural carrier of the account, budget and logs, and revocation works immediately.
  • Access to your own resources: OAuth2 shines when delegating access to a user's data (e.g. "sign in with Google"), and that isn't the case here.

Large providers combine both models: an API key for server-to-server calls, OAuth2 where there is delegation. That is why an API key isn't a "worse" choice, just a different trade-off. The choice for a price list: a few trusted clients and a quick start: an API key (a hash in the database, scopes, limits, revocation, HTTPS); more clients, standard libraries on their side, plans for growth: an OAuth2 server (C).

A working example - OpenIddictDemo

A single .NET 8 application is at once the authorization server (OpenIddict, clients in SQLite) and the API with the price list. Port 5004, HTTPS only (dotnet dev-certs https --trust). Two clients: acme-pricing (read only) and partner-admin (read and write). The full project is in examples/OpenIddictDemo, the scenario in requests.http.

using System.Collections.Concurrent;
using System.Security.Claims;
using System.Threading.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using OpenIddict.Abstractions;
using OpenIddict.Server.AspNetCore;
using OpenIddict.Validation.AspNetCore;
using static OpenIddict.Abstractions.OpenIddictConstants;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<AppDb>(o =>
{
    o.UseSqlite("Data Source=openiddict.db");
    o.UseOpenIddict(); // adds the OpenIddict tables: applications (clients), scopes, tokens, authorizations
});

builder.Services.AddOpenIddict()
    .AddCore(o => o.UseEntityFrameworkCore().UseDbContext<AppDb>())
    .AddServer(o =>
    {
        o.SetTokenEndpointUris("connect/token");
        o.AllowClientCredentialsFlow();                       // machine-to-machine: client_id + client_secret -> access token
        o.RegisterScopes("pricing:read", "pricing:write");
        o.SetAccessTokenLifetime(TimeSpan.FromMinutes(10));   // short, because there is no refresh token in this flow

        // DEMO ONLY: keys are regenerated on every start. In production use real certificates or keys from a vault.
        o.AddEphemeralEncryptionKey().AddEphemeralSigningKey();
        o.DisableAccessTokenEncryption();                     // readable JWT (e.g. on jwt.io), good for learning

        o.UseAspNetCore().EnableTokenEndpointPassthrough();   // we build the token ourselves in /connect/token below
    })
    .AddValidation(o =>
    {
        o.UseLocalServer(); // the API is in the same app as the server, so it trusts it directly
        o.UseAspNetCore();
    });

builder.Services.AddAuthentication(OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme);
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("pricing:read", p => p.RequireAssertion(c => c.User.HasScope("pricing:read")))
    .AddPolicy("pricing:write", p => p.RequireAssertion(c => c.User.HasScope("pricing:write")));

// Rate limit PER CLIENT (partition by the token subject): the real risk of a price list is mass downloading.
builder.Services.AddRateLimiter(o =>
{
    o.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
    o.AddPolicy("per-client", ctx => RateLimitPartition.GetFixedWindowLimiter(
        ctx.User.FindFirstValue(Claims.Subject) ?? "anonymous",
        _ => new FixedWindowRateLimiterOptions { PermitLimit = 5, Window = TimeSpan.FromMinutes(1) }));
});

builder.Services.AddHostedService<Seeder>(); // creates the database and two demo clients

var app = builder.Build();

if (!app.Environment.IsDevelopment()) app.UseHsts();
app.UseHttpsRedirection(); // the demo runs on https only (OpenIddict itself refuses to work over plain http)
app.UseAuthentication();
app.UseRateLimiter();
app.UseAuthorization();

// Token endpoint. By the time we get here OpenIddict has ALREADY checked client_id, the client_secret
// (against its hash in the database), the grant type and whether the client may request the scopes.
app.MapPost("/connect/token", async (HttpContext http, IOpenIddictApplicationManager apps) =>
{
    var request = http.GetOpenIddictServerRequest()
        ?? throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");

    if (!request.IsClientCredentialsGrantType())
        return Results.BadRequest(new { error = Errors.UnsupportedGrantType });

    var application = await apps.FindByClientIdAsync(request.ClientId!)
        ?? throw new InvalidOperationException("The application cannot be found.");

    var identity = new ClaimsIdentity(TokenValidationParameters.DefaultAuthenticationType, Claims.Name, Claims.Role);
    identity.SetClaim(Claims.Subject, await apps.GetClientIdAsync(application));
    identity.SetClaim(Claims.Name, await apps.GetDisplayNameAsync(application));
    identity.SetScopes(request.GetScopes());                    // what the client asked for (and is allowed to get)
    identity.SetDestinations(_ => [Destinations.AccessToken]);  // put every claim into the access token

    return Results.SignIn(new ClaimsPrincipal(identity), properties: null, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
});

// The business API: a price list. Access is decided by SCOPES from the token.
var prices = new ConcurrentDictionary<string, decimal>
{
    ["SKU-100"] = 19.99m,
    ["SKU-200"] = 49.90m,
    ["SKU-300"] = 129.00m
};

app.MapGet("/api/prices", (ClaimsPrincipal user) => new { client = user.FindFirstValue(Claims.Subject), prices })
    .RequireAuthorization("pricing:read")
    .RequireRateLimiting("per-client");

app.MapPut("/api/prices/{sku}", (string sku, PriceUpdate update) =>
{
    prices[sku] = update.Price;
    return Results.NoContent();
})
    .RequireAuthorization("pricing:write")
    .RequireRateLimiting("per-client");

app.Run();

record PriceUpdate(decimal Price);
using Microsoft.EntityFrameworkCore;
using OpenIddict.Abstractions;
using static OpenIddict.Abstractions.OpenIddictConstants;

public class AppDb(DbContextOptions<AppDb> options) : DbContext(options)
{
}

// Creates the database and two demo clients on startup (in production clients are added by an admin panel or a script).
public class Seeder(IServiceProvider services) : IHostedService
{
    public async Task StartAsync(CancellationToken ct)
    {
        await using var scope = services.CreateAsyncScope();
        await scope.ServiceProvider.GetRequiredService<AppDb>().Database.EnsureCreatedAsync(ct); // demo: no migrations
        var apps = scope.ServiceProvider.GetRequiredService<IOpenIddictApplicationManager>();

        await EnsureClientAsync(apps, "acme-pricing", "Acme Sp. z o.o.", "acme-secret-change-me",
            new[] { "pricing:read" }, ct);
        await EnsureClientAsync(apps, "partner-admin", "Partner Admin", "admin-secret-change-me",
            new[] { "pricing:read", "pricing:write" }, ct);
    }

    private static async Task EnsureClientAsync(IOpenIddictApplicationManager apps, string clientId, string displayName,
        string secret, string[] scopes, CancellationToken ct)
    {
        if (await apps.FindByClientIdAsync(clientId, ct) is not null) return;

        var descriptor = new OpenIddictApplicationDescriptor
        {
            ClientId = clientId,
            ClientSecret = secret,                 // OpenIddict stores only a HASH of the secret
            DisplayName = displayName,
            ClientType = ClientTypes.Confidential,
            Permissions =
            {
                Permissions.Endpoints.Token,
                Permissions.GrantTypes.ClientCredentials
            }
        };
        foreach (var scope in scopes) descriptor.Permissions.Add(Permissions.Prefixes.Scope + scope);

        await apps.CreateAsync(descriptor, ct);
    }

    public Task StopAsync(CancellationToken ct) => Task.CompletedTask;
}

How to try it

dotnet dev-certs https --trust   # once
dotnet run

# token for the read-only client
curl -k -X POST https://localhost:5004/connect/token \
     -d "grant_type=client_credentials&client_id=acme-pricing&client_secret=acme-secret-change-me&scope=pricing:read"

# call the API with the access_token from the answer
curl -k https://localhost:5004/api/prices -H "Authorization: Bearer <access_token>"

# the same token cannot change prices -> 403
curl -k -X PUT https://localhost:5004/api/prices/SKU-100 -H "Authorization: Bearer <access_token>" \
     -H "Content-Type: application/json" -d '{"price":17.5}'

What this example shows

  • The client secret is in the database as a hash (OpenIddict takes care of this). /connect/token gets the request only after the client, secret and scopes have been checked.
  • Scopes decide access: read gets pricing:read, write requires pricing:write. A wrong secret gives 401 invalid_client, a disallowed scope 400 invalid_scope, a missing scope in the token 403.
  • A limit of 5 requests per minute per client (partitioned by sub from the token) ends with a 429 response.
  • No refresh token: expires_in is 600 s and the client simply fetches a new token.

The client side at the company: fetching and caching the token

using System.Net.Http.Json;
using System.Text.Json.Serialization;

// Fetches a token, keeps it until shortly before it expires, and reuses it for every API call.
public class PricingTokenProvider(HttpClient http, string clientId, string clientSecret)
{
    private string? _token;
    private DateTime _expiresAtUtc;

    public async Task<string> GetTokenAsync()
    {
        if (_token is not null && DateTime.UtcNow < _expiresAtUtc) return _token;

        var response = await http.PostAsync("connect/token", new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["grant_type"] = "client_credentials",
            ["client_id"] = clientId,
            ["client_secret"] = clientSecret,
            ["scope"] = "pricing:read"
        }));
        response.EnsureSuccessStatusCode();

        var body = await response.Content.ReadFromJsonAsync<TokenResponse>()!;
        _token = body!.AccessToken;
        _expiresAtUtc = DateTime.UtcNow.AddSeconds(body.ExpiresIn - 30); // refresh a bit early
        return _token;
    }
}

public record TokenResponse(
    [property: JsonPropertyName("access_token")] string AccessToken,
    [property: JsonPropertyName("expires_in")] int ExpiresIn);

In practice the client will use a ready-made library (e.g. access token management from Duende.AccessTokenManagement or an equivalent in its language), which does the same and handles parallel calls.

The most common pitfalls

  • The client secret in a repository, logs or a URL.
  • No request limits - one client can download the whole price list.
  • A long access token with no way to revoke it - a stolen one works until it expires.
  • Scopes that are too broad for all clients instead of minimal ones.
  • HTTP with a redirect to HTTPS instead of rejection - the secret has time to leak.
  • Your own token server in production without a security audit.
  • The same signing key pair forever - no rotation and no plan for a key leak.

Interview questions

  • Which OAuth2 flow for server-to-server communication? Client Credentials: the client authenticates with a secret (or a certificate) and gets an access token, with no user.
  • Is a refresh token used in Client Credentials? Usually not. The client holds the secret and fetches a new access token, so the access token is short.
  • An API key or OAuth2? For a few trusted clients an API key is simpler; with many clients, scopes and an expectation of a standard, OAuth2 is better (e.g. OpenIddict, Keycloak).
  • How do you limit a client's permissions? With scopes granted in the database and checked in authorization policies.
  • How do you protect the client secret in the database? You store only the hash, and show the secret itself to the client once.
  • How do you prevent mass data download? Request limits per client, monitoring and alerts.
  • Is JWT part of OAuth2? No. OAuth2 doesn't specify the token format; an access token can be a JWT or opaque. The ID token in OpenID Connect is always a JWT.
  • How does OIDC differ from OAuth2? OAuth2 is authorization (access to resources), and OIDC adds user authentication: the ID token, userinfo, discovery.
  • What is OpenIddict? A framework for building your own OAuth2/OIDC server in ASP.NET Core, not a ready-made product (unlike Keycloak).
  • Why not call your own token endpoint OAuth2? Because the name promises compliance with the RFC and working with standard libraries; deviations and your own security bugs break that promise.
  • Can one API support an API key and OAuth2? Yes, through several authentication schemes (or a policy scheme), provided both build the same model of claims and scopes.
  • Do OAuth2/OIDC have an API for managing clients? There is no standard apart from Dynamic Client Registration; every server has its own (the Keycloak Admin API, Graph, the Management API) or, as with OpenIddict, you do it with your own code.
  • Why should an access token be short? Because the role or scope is frozen in it, and revoking an individual token is hard.

See also

Buy me a coffee