Identity.Base Docs
Identity.Base.ServicePrincipals
`Identity.Base.ServicePrincipals` adds database-backed machine identities to an Identity Base host. Each principal has an immutable subject and client ID, independently revocable credentials, global RBAC roles, and short-lived OAuth 2.0 client-credentials tokens.
Managed identity model
- Principal: generated immutable `Guid` subject and client ID with an operator-controlled display name.
- Credentials: issue several secrets, rotate them independently, and revoke one or all.
- Authorization: assign the same global roles and permission catalog used for users.
- Tokens: use `client_credentials`; no user session or refresh token is involved.
Use it for
- Workers, schedulers, integration services, and deployment automation.
- Workloads that need RBAC permissions without impersonating a user.
- Credential rotation where old and new secrets overlap briefly.
- Operator-managed machine identities rather than configuration-seeded clients.
Install and wire the package
dotnet add package Identity.Base.ServicePrincipals using Identity.Base.Admin.Configuration;
using Identity.Base.Admin.Endpoints;
using Identity.Base.Extensions;
using Identity.Base.Roles.Endpoints;
using Identity.Base.ServicePrincipals.Extensions;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
var configureDbContext =
new Action<IServiceProvider, DbContextOptionsBuilder>((sp, options) =>
{
var connectionString = sp.GetRequiredService<IConfiguration>()
.GetConnectionString("Primary")
?? throw new InvalidOperationException("ConnectionStrings:Primary must be set.");
options.UseNpgsql(connectionString); // or UseSqlServer(connectionString)
});
builder.Services.AddIdentityBase(
builder.Configuration,
builder.Environment,
configureDbContext: configureDbContext);
builder.Services.AddIdentityAdmin(builder.Configuration, configureDbContext);
builder.Services.AddIdentityBaseServicePrincipals(
builder.Configuration,
configureDbContext);
var app = builder.Build();
app.UseApiPipeline();
app.MapApiEndpoints();
app.MapIdentityAdminEndpoints();
app.MapIdentityRolesUserEndpoints();
app.MapIdentityBaseServicePrincipalEndpoints(); Register the core and admin/RBAC layers first. The service-principal package is optional and does not replace configuration-seeded OpenIddict applications.
Configure token policy
{
"Identity": {
"ServicePrincipals": {
"AccessTokenLifetime": "00:15:00",
"AllowedScopes": ["identity.api"]
}
}
} The access-token lifetime defaults to 15 minutes. Every allowed scope must also exist under OpenIddict:Scopes. Changes to allowed scopes affect newly created managed clients; existing application permissions are not rewritten automatically.
Generate both host-owned migrations
dotnet ef migrations add AddServicePrincipals \
--context Identity.Base.ServicePrincipals.Data.ServicePrincipalDbContext \
--output-dir Data/Migrations/ServicePrincipals
dotnet ef migrations add AddServicePrincipalRoles \
--context Identity.Base.Roles.IdentityRolesDbContext \
--output-dir Data/Migrations/Roles
dotnet ef database update \
--context Identity.Base.ServicePrincipals.Data.ServicePrincipalDbContext
dotnet ef database update \
--context Identity.Base.Roles.IdentityRolesDbContext The feature spans two contexts: ServicePrincipalDbContext stores principals and credentials, while the updated IdentityRolesDbContext stores service-principal role assignments. Add the roles migration to the existing roles migration chain.
| Method and route | Purpose | Permission |
|---|---|---|
| GET /admin/service-principals | Paged list with page, pageSize, search, and disabled filters | `service-principals.read` |
| GET /admin/service-principals/{id} | Read one principal and its role names | `service-principals.read` |
| POST /admin/service-principals | Create a principal and generated immutable client ID | `service-principals.create` |
| PUT /admin/service-principals/{id} | Update display name with the current concurrency stamp | `service-principals.update` |
| POST /admin/service-principals/{id}/disable | Disable and revoke all credentials and token entries | `service-principals.disable` |
| POST /admin/service-principals/{id}/restore | Re-enable the principal; credentials stay revoked | `service-principals.disable` |
| GET /admin/service-principals/{id}/roles | Read assigned global roles | `service-principals.read` |
| PUT /admin/service-principals/{id}/roles | Replace assigned global roles | `service-principals.manage-roles` |
| GET /admin/service-principals/{id}/credentials | List credential metadata without secrets | `service-principals.read` |
| POST /admin/service-principals/{id}/credentials | Issue a named credential with optional expiry | `service-principals.manage-credentials` |
| POST /admin/service-principals/{id}/credentials/{credentialId}/revoke | Revoke one credential | `service-principals.manage-credentials` |
| POST /admin/service-principals/{id}/credentials/revoke-all | Revoke all credentials and token entries | `service-principals.manage-credentials` |
List page size is clamped to 1–100. Updates use optimistic concurrency and return 409 Conflict for a stale stamp. Client IDs cannot be edited.
Provision safely
- Create the principal at
POST /admin/service-principals. - Assign a least-privilege global role.
- Issue a named credential with an expiration.
- Copy the returned secret directly to an approved secret store.
The issue response is the only response containing the plaintext secret. Identity Base stores only a password hash and cannot recover the value later.
Request a token
curl -sS https://identity.example.com/connect/token \
-u "$CLIENT_ID:$CLIENT_SECRET" \
-H 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'scope=identity.api' Tokens include sub, client_id, identity.principal_type=ServicePrincipal, and role-derived identity.permissions.
TypeScript administration
const principal = await authManager.admin.servicePrincipals.create({
displayName: 'Invoice Worker',
})
await authManager.admin.servicePrincipals.updateRoles(
principal.id,
['InvoiceWorker'],
)
const issued = await authManager.admin.servicePrincipals.issueCredential(
principal.id,
{ name: 'production', expiresAt: '2027-01-01T00:00:00Z' },
)
// Persist issued.secret now; it cannot be retrieved later. The complete typed surface is available from IdentityAuthManager.admin.servicePrincipals and is re-exported by the framework clients.
Lifecycle and extension points
- Register
IServicePrincipalLifecycleListenerfor product-specific governance before disable; reject the operation withInvalidOperationExceptionto return a conflict. - Use the package builder’s
ConfigureModel(...)for EF model customization orUseDbContext<TContext>()for a registered derived context. IClientCredentialsPrincipalProviderandIManagedClientCredentialsClientResolversupport alternative managed-client sources.- Lifecycle, role, and credential operations emit audit events through the host’s
IAuditLogger.
Revocation boundary
Disable and revoke-all invalidate stored token entries, and the Identity host checks those entries. A downstream API performing only offline validation of a self-contained JWT cannot observe the database change before the token expires. Keep machine tokens short-lived or use online validation where immediate downstream revocation is required. Restoring a principal never restores its credentials.