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

bash
dotnet add package Identity.Base.ServicePrincipals
csharp
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

json
{
  "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

bash
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
GET /admin/service-principalsPaged list with page, pageSize, search, and disabled filters
GET /admin/service-principals/{id}Read one principal and its role names
POST /admin/service-principalsCreate a principal and generated immutable client ID
PUT /admin/service-principals/{id}Update display name with the current concurrency stamp
POST /admin/service-principals/{id}/disableDisable and revoke all credentials and token entries
POST /admin/service-principals/{id}/restoreRe-enable the principal; credentials stay revoked
GET /admin/service-principals/{id}/rolesRead assigned global roles
PUT /admin/service-principals/{id}/rolesReplace assigned global roles
GET /admin/service-principals/{id}/credentialsList credential metadata without secrets
POST /admin/service-principals/{id}/credentialsIssue a named credential with optional expiry
POST /admin/service-principals/{id}/credentials/{credentialId}/revokeRevoke one credential
POST /admin/service-principals/{id}/credentials/revoke-allRevoke all credentials and token entries

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

  1. Create the principal at POST /admin/service-principals.
  2. Assign a least-privilege global role.
  3. Issue a named credential with an expiration.
  4. 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

bash
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

ts
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 IServicePrincipalLifecycleListener for product-specific governance before disable; reject the operation with InvalidOperationException to return a conflict.
  • Use the package builder’s ConfigureModel(...) for EF model customization or UseDbContext<TContext>() for a registered derived context.
  • IClientCredentialsPrincipalProvider and IManagedClientCredentialsClientResolver support 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.