Claude
Skills
Sign in
Back

identityserver-sessions-providers

Included with Lifetime
$97 forever

Guide for configuring server-side sessions, session management and querying, inactivity timeout, dynamic identity providers, and CIBA (Client Initiated Backchannel Authentication) in Duende IdentityServer.

General

What this skill does


# IdentityServer Sessions, Dynamic Providers, and CIBA

## When to Use This Skill

- Enabling and configuring server-side sessions for authentication state management
- Implementing session querying, revocation, and administrative tooling via `ISessionManagementService`
- Configuring inactivity timeout across IdentityServer and client applications
- Setting up the Entity Framework Core session store or implementing a custom `IServerSideSessionStore`
- Adding dynamic identity providers loaded from a database at runtime
- Implementing custom non-OIDC dynamic provider types (Google, SAML, etc.)
- Building a CIBA (Client Initiated Backchannel Authentication) flow
- Understanding edition requirements (Business vs Enterprise) for these features

Docs: https://docs.duendesoftware.com/identityserver/ui/sessions

## Server-Side Sessions

### What Problem Do They Solve?

By default, ASP.NET Core stores all authentication session state in a self-contained cookie. This creates several challenges:

| Problem                      | Impact                                                                            |
| ---------------------------- | --------------------------------------------------------------------------------- |
| Cookie size growth           | As clients are tracked, the cookie grows; large cookies can exceed browser limits |
| No session visibility        | Cannot query how many active sessions exist                                       |
| No administrative revocation | Cannot terminate a session from outside the user's browser                        |
| No server-side coordination  | Cannot detect inactivity or synchronize session expiration across clients         |

Server-side sessions store authentication state on the server, keeping only a session reference in the cookie.

### Edition Requirements

Server-side sessions are part of the **Duende IdentityServer Business and Enterprise Edition**.

### Enabling Server-Side Sessions

```csharp
// Program.cs
builder.Services.AddIdentityServer()
    .AddServerSideSessions();
```

**Important**: This call must come after any custom `IRefreshTokenService` implementation registration. Order matters in the ASP.NET Core service provider.

By default, sessions are stored in-memory. For production, use Entity Framework Core or a custom store.

### Using Entity Framework Core Store

```csharp
// Program.cs
builder.Services.AddIdentityServer()
    .AddServerSideSessions()
    .AddOperationalStore(options =>
    {
        options.ConfigureDbContext = builder =>
            builder.UseSqlServer(connectionString,
                sql => sql.MigrationsAssembly(migrationsAssembly));
    });
```

The EF Core implementation is included in the operational store and supports the `IServerSideSessionStore` interface automatically.

### Custom Session Store

Implement `IServerSideSessionStore` and register it:

```csharp
// Program.cs — two-step registration
builder.Services.AddIdentityServer()
    .AddServerSideSessions()
    .AddServerSideSessionStore<YourCustomStore>();

// Or one-step registration
builder.Services.AddIdentityServer()
    .AddServerSideSessions<YourCustomStore>();
```

### Data Stored Server-Side

The session stores the serialized ASP.NET Core `AuthenticationTicket` (all claims + `AuthenticationProperties.Items`). The data is protected using ASP.NET Core's Data Protection API.

Queryable indices extracted from the session:

| Index        | Source                                            |
| ------------ | ------------------------------------------------- |
| Subject ID   | `sub` claim value                                 |
| Session ID   | `sid` claim value                                 |
| Display Name | Configurable claim type (e.g., `name` or `email`) |

Configure the display name claim. **Note**: `UserDisplayNameClaimType` is **unset (null) by default** due to PII concerns. You must explicitly set it if you want display names stored in the session index:

```csharp
// Program.cs
builder.Services.AddIdentityServer(options => {
    options.ServerSideSessions.UserDisplayNameClaimType = "name";
}).AddServerSideSessions();
```

## Session Management with ISessionManagementService

### Querying Sessions

```csharp
var userSessions = await _sessionManagementService.QuerySessionsAsync(new SessionQuery
{
    CountRequested = 10,
    SubjectId = "12345",
    DisplayName = "Bob",
});
```

### Paging Through Results

```csharp
// First page
var userSessions = await _sessionManagementService.QuerySessionsAsync(new SessionQuery
{
    CountRequested = 10,
});

// Next page
userSessions = await _sessionManagementService.QuerySessionsAsync(new SessionQuery
{
    ResultsToken = userSessions.ResultsToken,
    CountRequested = 10,
});

// Previous page
userSessions = await _sessionManagementService.QuerySessionsAsync(new SessionQuery
{
    ResultsToken = userSessions.ResultsToken,
    RequestPriorResults = true,
    CountRequested = 10,
});
```

### Performance Note on Querying

When listing sessions, prefer `GetSessionsAsync` over `QuerySessionsAsync`. The `QuerySessionsAsync` method performs a full-text search and may be slower. Use `QuerySessionsAsync` only when advanced filtering is needed.

### Terminating Sessions

Terminate sessions and optionally revoke tokens, consents, and send back-channel logout notifications:

```csharp
// Revoke everything for a user
await _sessionManagementService.RemoveSessionsAsync(new RemoveSessionsContext
{
    SubjectId = "12345"
});
```

Selective revocation (filtering by `SessionId` or `ClientIds` is also supported):

```csharp
// Only revoke refresh tokens, keep session and consents
await _sessionManagementService.RemoveSessionsAsync(new RemoveSessionsContext
{
    SubjectId = "12345",
    SessionId = "abc123",        // optional: target a specific session
    ClientIds = { "my_app" },    // optional: target specific clients
    RevokeTokens = true,
    RemoveServerSideSession = false,
    RevokeConsents = false,
    SendBackchannelLogoutNotification = false,
});
```

### What Gets Cleaned Up

| Flag                                                | Effect                                                           |
| --------------------------------------------------- | ---------------------------------------------------------------- |
| `RemoveServerSideSession` (default: true)           | Deletes the session record from the store                        |
| `RevokeTokens` (default: true)                      | Revokes refresh tokens and reference access tokens               |
| `RevokeConsents` (default: true)                    | Removes persisted consent grants                                 |
| `SendBackchannelLogoutNotification` (default: true) | Sends back-channel logout to clients with `BackChannelLogoutUri` |

Internally, this uses `IServerSideTicketStore`, `IPersistedGrantStore`, and `IBackChannelLogoutService`.

## Inactivity Timeout

### The Challenge

OpenID Connect does not natively provide distributed session management based on user inactivity. Multiple artifacts (cookies, refresh tokens, access tokens) have independent lifetimes controlled by different entities. Coordinating their expiration is non-trivial.

### Design: Centralized Session Tracking

Server-side sessions at IdentityServer provide the central record for monitoring user activity:

1. **Activity signals**: As the user's client uses refresh tokens, introspection, or userinfo, these protocol calls extend the server-side session automatically via an internal `ISessionCoordinationService` (this is an implementation detail, not a public API for consumers).
2. **Inactivity detection**: When no activity occurs within the session timeout, the session expires and cleanup is triggered (back-channel logout, token revocation).

### Configuration at IdentityServer

Three features must be enabled:

```csharp
// Program.cs
builder.Services.AddIdentityServer(options =>
{
    // 1. Enable server-side ses

Related in General