# SAIF.Platform.Authentication

Framework-agnostic token-acquisition and auth-client building blocks, shared between internal ("Corp", Entra ID) and external (Okta) tenants. This package has no ASP.NET Core dependency — for middleware that wires these clients into an ASP.NET Core pipeline, see [`SAIF.Platform.Authentication.AspNetCore`](../SAIF.Platform.Authentication.AspNetCore/index.md).

## Getting started

Register the authentication configuration for a tenant, then the matching token client for the flow you need:

```csharp
builder.AddAuthenticationConfiguration(projectId, AuthTenants.Corp, scopes);
builder.AddCorpOAuthTokenAuthenticationClient();
```

Pick the `Add*TokenAuthenticationClient` call that matches your tenant and flow:

- `AddCorpOAuthTokenAuthenticationClient()` — Entra ID, OAuth client credentials.
- `AddCorpOpenIdConnectTokenAuthenticationClient()` — Entra ID, OpenID Connect.
- `AddExternalOAuthTokenAuthenticationClient()` — Okta, OAuth client credentials.
- `AddExternalOpenIdConnectTokenAuthenticationClient()` — Okta, OpenID Connect.

Each reads its client ID/secret from configuration (e.g. `OAuthClientId_corp` / `OAuthClientSecret_corp`) and registers a keyed `TokenAuthenticationClient` under the matching `AuthenticationSchemes` key. `AddAuthenticationServices()` is a convenience wrapper that registers all four clients plus the token cache and discovery cache in one call.

## Concepts

- **`AuthTenants`** — the two supported identity provider origins: `Corp` (Entra ID, internal) and `External` (Okta, external). Most APIs take an `authTenant` string parameter using these constants to route configuration keys, scopes, and client registration to the right identity provider.
- **`AuthenticationConfiguration`** — per-project, per-tenant authority/audience/scopes, resolved from `Services:{projectId}:{authTenant}:authserver` and `...:authserveraudience` configuration keys, with hot-reload on configuration changes. Also holds token cache tuning (safety buffer, max duration, sliding expiration).
- **`ScopeBuilder`** — builds correctly prefixed scopes per tenant: `api://{projectId}-{environmentName}/{scope}` for Corp, `{projectId}.{scope}` for External. It auto-appends the tenant's delegated permission scope (`user_impersonation` for Corp, `user-groups` for External) unless disabled, and has a separate `BuildForClientCredentials` for the client-credentials flow (Corp always uses `.default`).

## Related packages

- [`SAIF.Platform.Authentication.AspNetCore`](../SAIF.Platform.Authentication.AspNetCore/index.md) — ASP.NET Core middleware built on top of these clients.

---

[View source on GitHub](https://github.com/saif-corp/forge/blob/main/src/dotnet/SAIF.Platform.Authentication/README.md)
