Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 13 · Lesson 127 · 8 min read

Building Public APIs for Mobile and Third Parties

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: Issuing and Verifying API Keys, Quotas per Key and Deprecation Headers
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Design an API for external developers and mobile apps, choose between API keys and OAuth, store and verify API keys safely, apply quotas and deprecation policy, and use the correct OAuth flows and storage for native mobile clients.

Concept Explanation

An API used only by your own React app can change whenever your team does. A public API is a product: outside developers build on it, cannot be forced to upgrade, and judge you by its stability and documentation. That changes priorities. Contracts must be stable and versioned as in Day 25, with a written deprecation policy that gives a long, announced notice period and machine-readable signals, such as the Sunset header from RFC 8594 and the newer Deprecation header. Documentation comes from the OpenAPI document of Day 18, supplemented with guides, examples, and generated SDKs. A sandbox environment with test data lets developers try things without risk, and predictable errors, pagination, and idempotency keys as in earlier lessons make integration less painful. Quotas and rate limits are part of the product: publish them, return 429 with Retry-After, and let plans define limits.

Identification and authorization come in two shapes. An API key identifies a calling application, and is suited to server-to-server integrations where a developer acts for their own account. It is a bearer secret, so treat it like a password: generate it with a cryptographically secure random source, show it once, store only a hash, allow multiple keys per account so they can be rotated, support revocation and expiry, and scope each key to what it needs. Because a key has high entropy, a fast hash such as SHA-256 is adequate for storage, unlike passwords, and a short visible prefix lets users identify a key in a dashboard and lets you look it up before comparing hashes in constant time. OAuth 2.0 is the right choice when a third-party application acts on behalf of your users: the user grants specific scopes in a consent screen, the app receives tokens limited to those scopes, and the user can revoke access. Register clients, require exact redirect URI matching, use the authorization code flow with PKCE, and follow the current OAuth security best practices.

Mobile apps are a special kind of client. They are public clients, meaning they cannot keep a secret, since anything embedded in an app binary can be extracted, so an API key or client secret compiled into the app is not a secret. Follow the guidance for native apps in RFC 8252: use the authorization code flow with PKCE in the system browser, not an embedded web view where the app could capture credentials, and receive the result through a registered redirect. Store tokens in the platform's secure storage, the iOS Keychain and Android Keystore, keep access tokens short-lived, and use refresh token rotation so a stolen refresh token is detected. Certificate pinning can raise the bar for interception but makes certificate rotation harder, so use it deliberately. App attestation services, Apple App Attest and Google Play Integrity, provide a signal that requests come from a genuine app on a genuine device, useful against abuse but never a replacement for server-side authorization. Since mobile users update slowly, the API must support old app versions for a long time, and a minimum supported version check lets you retire dangerous ones.

The stakes of third-party access are visible in history. Broad permissions granted to one app can expose the data of many people, so request the smallest scopes, review what developers can request, and audit apps. Also log and monitor API key usage per key, alert on anomalies, and provide a way for customers to see and revoke access.

TopicGuidanceReason
API keysRandom, shown once, stored hashed, scoped, revocableThey are bearer secrets
OAuth for third partiesAuthorization code with PKCE, scopes, consent, revocationActing on behalf of users needs their consent
Mobile clientsSystem browser, PKCE, secure storage, no embedded secretsPublic clients cannot keep secrets
DeprecationAnnounce, Sunset and Deprecation headers, long noticeOutside developers cannot upgrade instantly
QuotasPer key or client, plan based, 429 with Retry-AfterFair use and predictable cost
Old app versionsSupport long, enforce a minimum version when neededUsers update slowly

Worked Example: Issuing and Verifying API Keys, Quotas per Key and Deprecation Headers

The code issues a key, authenticates it in a handler, partitions limits by key, and adds deprecation headers.

C#
// Issue: high-entropy secret, shown once, only a hash is stored.
public static (string PlainKey, ApiKey Record) Issue(Guid accountId, string[] scopes, string name)
{
    var prefix = Base32(RandomNumberGenerator.GetBytes(6));                 // identifies the key in a dashboard and for lookup
    var secret = Base32(RandomNumberGenerator.GetBytes(32));                // 256 bits of randomness
    var plain  = $"acme_live_{prefix}_{secret}";
    var record = new ApiKey
    {
        AccountId = accountId, Name = name, Prefix = prefix, Scopes = scopes,
        Hash = SHA256.HashData(Encoding.UTF8.GetBytes(secret)),             // fast hash is fine for a random 256-bit secret
        ExpiresAt = DateTimeOffset.UtcNow.AddYears(1),
    };
    return (plain, record);                                                 // return plain once, then it is unrecoverable
}

// Authenticate: look up by prefix, compare the hash in constant time, check state and scope.
public sealed class ApiKeyHandler(AppDb db, IOptionsMonitor<AuthenticationSchemeOptions> o, ILoggerFactory l, UrlEncoder e)
    : AuthenticationHandler<AuthenticationSchemeOptions>(o, l, e)
{
    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        if (!Request.Headers.TryGetValue("Authorization", out var h) || !h.ToString().StartsWith("Bearer acme_live_")) return AuthenticateResult.NoResult();
        var parts = h.ToString()["Bearer acme_live_".Length..].Split('_');
        if (parts.Length != 2) return AuthenticateResult.Fail("Malformed key");

        var key = await db.ApiKeys.AsNoTracking().SingleOrDefaultAsync(k => k.Prefix == parts[0] && k.RevokedAt == null && k.ExpiresAt > DateTimeOffset.UtcNow);
        var candidate = SHA256.HashData(Encoding.UTF8.GetBytes(parts[1]));
        if (key is null || !CryptographicOperations.FixedTimeEquals(candidate, key.Hash)) return AuthenticateResult.Fail("Invalid key");

        var identity = new ClaimsIdentity(key.Scopes.Select(s => new Claim("scope", s)).Append(new Claim("account_id", key.AccountId.ToString())), Scheme.Name);
        return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name));
    }
}
C#
// Quotas per key and plan, with standard responses. The partition is the account, not the IP address.
builder.Services.AddRateLimiter(o =>
{
    o.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
    o.OnRejected = (ctx, _) => { ctx.HttpContext.Response.Headers.RetryAfter = "30"; return ValueTask.CompletedTask; };
    o.AddPolicy("public-api", ctx =>
    {
        var account = ctx.User.FindFirstValue("account_id") ?? ctx.Connection.RemoteIpAddress?.ToString() ?? "anon";
        var perMinute = PlanLimits.For(ctx.User.FindFirstValue("plan")).RequestsPerMinute;
        return RateLimitPartition.GetTokenBucketLimiter(account, _ => new TokenBucketRateLimiterOptions
        { TokenLimit = perMinute, TokensPerPeriod = perMinute, ReplenishmentPeriod = TimeSpan.FromMinutes(1), QueueLimit = 0 });
    });
});

// Deprecation policy in the response headers so client tooling and humans can see it coming.
app.Use(async (ctx, next) =>
{
    if (ctx.Request.Path.StartsWithSegments("/v1"))
    {
        ctx.Response.Headers["Deprecation"] = "true";
        ctx.Response.Headers["Sunset"] = "Wed, 30 Jun 2027 00:00:00 GMT";                       // announced well in advance
        ctx.Response.Headers.Append("Link", "</docs/migrate-v1-to-v2>; rel=\"deprecation\"");
    }
    await next();
});

// Scope checks are ordinary authorization policies, not special cases in each handler.
builder.Services.AddAuthorizationBuilder().AddPolicy("tasks:write", p => p.RequireClaim("scope", "tasks:write"));
Code
Mobile sign-in (native app, public client):
  1. App opens the system browser to the authorize endpoint with code_challenge (PKCE) and a registered redirect (app link).
  2. User signs in and consents. The browser returns to the app with a one-time code.
  3. App exchanges the code plus code_verifier for tokens over TLS. No client secret exists in the app.
  4. Access token: short-lived, in memory. Refresh token: Keychain or Keystore, rotated on every use.
  5. Server: minimum supported app version, attestation signal as a risk input, authorization on every request as usual.

Show the full key only once in the dashboard, and consider the secret-scanning partnership that many providers offer, so keys leaked to public repositories are reported and revoked automatically.

Outside developers need a stable contract with documentation and a sandbox, an identity model that fits their use, published quotas, a long deprecation policy with machine-readable headers, and mobile clients that follow the public client rules with no embedded secrets.
Outside developers need a stable contract with documentation and a sandbox, an identity model that fits their use, published quotas, a long deprecation policy with machine-readable headers, and mobile clients that follow the public client rules with no embedded secrets.

Real-World Examples

  • In 2018 it emerged that a personality quiz app had used permissions available at the time in Facebook's platform to collect data on tens of millions of users, most of whom never used the app, and this was passed to Cambridge Analytica. The Federal Trade Commission later imposed a five billion dollar penalty on Facebook, and the platform sharply restricted third-party access, a costly demonstration that broad scopes and weak review of third parties are a product risk.
  • In 2023 Twitter ended free access to its API and introduced paid tiers on short notice, breaking many third-party clients and research tools that depended on it. It is the standard illustration of why a public API needs a stable, announced policy, and of the business risk for developers who build on one.
Key TakeawaysTreat a public API as a product with stable contracts, documentation, sandbox, published quotas, and a long, machine-readable deprecation policy. Store API keys hashed with a prefix for lookup, scope and rotate them, use OAuth with PKCE and consent when acting for users, and treat mobile apps as public clients with the system browser, secure storage, rotation, and no embedded secrets.

Review Questions & Answers

An API key is a long random secret with very high entropy, so guessing it is infeasible even with a fast hash, while passwords are short and guessable and need a deliberately slow function. Storing the hash still protects keys if the database leaks.

The app binary is in users' hands and can be unpacked and inspected, so anything embedded can be extracted. Mobile clients are public clients and rely on PKCE, user authentication, and server-side authorization instead of embedded secrets.

An embedded web view lets the app see the user's credentials and gives up the browser's single sign-on session and protections. The system browser keeps the credentials with the identity provider, and the app receives only an authorization code.

It tells developers in advance, in a machine-readable way, that an endpoint will be removed and when, so their tooling can warn them and they can plan migration. Without notice, a removal breaks their applications unexpectedly.