# Authorize personal tokens and machine clients

Enforce live ownership, bounded credentials and trusted per-request IP allowlists.

Version 0.10.0 adds provider-neutral credential contracts to Application,
`CredentialService`/`CredentialNetworks` to Authentication, and the optional bearer
scheme/client_credentials endpoint to Authentication.AspNetCore. Legacy API-consumer
keys are unchanged; they are not silently migrated or reinterpreted as users.

## Choose a credential

| Scenario | Credential | Owner |
| --- | --- | --- |
| A user authorizes their own script | Personal bearer API token | Stable user in its identity authority |
| A confidential server integration | client_id/client_secret exchanged for a short-lived bearer token | Workload/service principal |
| Browser or distributed native app | Interactive session / public-client protocol | User; never embed a confidential client secret |

client_id is a public random selector; client_secret is a shared secret. This is
not an asymmetric public/private key pair. Asymmetric client authentication and
sender-constrained tokens are separate future profiles. This package is a bounded
client_credentials adapter, not an authorization server offering every OAuth grant.

## Compose the host

Register `AddFoundationCredentials`, a durable `ICredentialStore` and a live
`ICredentialAuthority`. There is no production in-memory fallback. The product
owns management endpoints, users/workloads, grants, credential quotas, migrations,
atomic audit, pruning and current tenant/company/app/license authorization.

`AuthorizeCreationAsync` checks a trusted current interactive management actor and
returns current owner admission. `TryCreateAsync` must recheck that actor's authority,
owner version, requested scopes and active limit under the same transaction as
insertion/audit. The service returns a secret only after the store commits. A PAT
or workload token must never construct its own privileged management actor.

Personal credentials must have user owners; machine clients must have workload
owners. Names, audience, scopes and lifetime are bounded. Default maximum lifetime
is 366 days, maximum active credentials per owner is 20, machine access lifetime is
5 minutes (configurable up to 15). Persist only the digest and selector; return the
random secret once. Use SHA-256 for 256-bit random secrets, never for passwords.
Record creation/revocation without raw secrets, access tokens or stored digests.

For HTTP, register `AddAuthentication().AddFoundationCredentialBearer(options =>
{ options.Audience = "product-api"; /* explicitly select client IP source */ })`,
add authorization policies that select `FoundationCredential` and require the
needed `scope` claims, and call `MapFoundationClientCredentials`. Configure the
named `FoundationCredentials` rate-limit policy and `UseRateLimiter` before serving
requests. Limit token requests per trusted client address/credential and the
protected APIs themselves. Register `UseAuthentication` and `UseAuthorization`.
Use the `CredentialIdentity` request feature,
or the namespaced credential owner-kind/authority/ID claims. No session assurance
or interactive MFA claim is emitted. Never identify users by subject ID alone
without their authority and owner kind.

The token endpoint requires HTTPS, form encoding, exactly `grant_type=client_credentials`
and a nonempty narrowed `scope`. HTTP Basic encodes URL-form-encoded client ID and
secret separated by a colon, then Base64. Alternatively send client_id/client_secret
in the form, exclusively. Duplicate fields, mixed authentication methods, query
parameters and unsupported grants are rejected. Responses have no-store/no-cache.
Secrets never belong in URLs. Successful responses contain access_token,
token_type=Bearer, expires_in and scope; refresh tokens are not issued.

Use HTTPS bearer authorization for protected API calls. The long-lived machine
client secret is rejected as an API bearer. Access tokens reference their parent;
`TryAddAccessAsync` must recheck parent/owner version and expiry atomically.
Each authentication reads current parent state and live owner admission. Revocation,
owner disablement/epoch changes, parent expiry and current IP policies therefore
apply to already-issued access tokens. Effective scopes intersect original token,
current credential and live owner grants. There is no stale admission cache.
Operation authorization must still validate grants in the transaction that changes
data; authentication alone does not serialize concurrent revocation with an API write.

## Trusted address and network policy

Select `CredentialClientIpSource.DirectSocket` only when the socket peer is the
actual caller, without IP-rewriting middleware. Behind the BFF select
`AuthenticatedBff` (default) and run `UseBffClientIp` before rate limiting and auth.
The BFF must overwrite the client-IP header, authenticate the forwarding secret,
use TLS and restrict direct backend access. Host-level automatic X-Forwarded-For
processing must remain disabled. Raw forwarded/Cloudflare headers are never used.

The middleware emits `BffClientIpFeature` only as server-side provenance. Missing
or invalid proof denies credential use instead of falling back to the proxy's
socket IP. DirectSocket mode rejects an enabled BFF forwarding pipeline. A missing
address denies even unrestricted credentials.

Network mode is explicit: Unrestricted with no networks, or AllowList with up to
64 IPv4/IPv6 addresses/networks. An empty AllowList denies all. Malformed/scoped
addresses, mapped CIDR networks and CIDRs with host bits are rejected. Single
IPv4-mapped addresses normalize to IPv4; IPv6 networks never implicitly cover IPv4.
Evaluate policy at exchange AND every API use. A leak outside allowed networks is
blocked; a compromised allowed host/shared NAT remains a risk. Changing a policy
must be an authorized, versioned, audited product command.

## Lifecycle and acceptance

Routine MFA maintenance and ordinary session logout do not automatically revoke
API credentials. Products explicitly choose recovery/global-compromise revocation
policy and change the credential owner epoch when required. Rotation creates a
new credential, permits deliberate bounded overlap, then revokes the old parent.
Prune expired access records, retain nonsecret audit, and avoid secret-bearing logs.

Tests exercise CSPRNG/digest-only persistence, user/workload separation, current
scope/epoch/admission, audience, expiry, revocation, IPv4/IPv6, policy changes,
TLS, duplicate forms, Basic exchange, bearer requests and forged/missing forwarding
proof through the actual ASP.NET pipeline. Product-owned persistence and authorized
management require their own real-database transaction/concurrency acceptance.

Protocol references: [OAuth client credentials](https://www.rfc-editor.org/rfc/rfc6749.html#section-4.4),
[OAuth security BCP](https://www.rfc-editor.org/rfc/rfc9700.html),
[trusted proxies](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-10.0).
