Path: redb-identity/demos/demo_me_sessions.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_me_sessions.ps1 ---- # Self-service session management — /api/v1/identity/me/sessions. # Bearer auth uses identity:account scope (not identity:manage). Caller can only # touch their own sessions; sub claim is the source of truth, never the body. # Coverage: GET list, DELETE /{id}, DELETE /others, DELETE /current. # # Sessions are OP sessions: each one is opened by an interactive POST /login (cookie). # A password grant (ROPC) opens none, so this demo signs in three "devices" through # /login and takes each device's token through authorization_code + PKCE; that token # carries the device's session id in the sid claim, which /others and /current use. # # What a revoke does: the session ends and its cookie no longer signs in silently at # /connect/authorize (prompt=none -> login_required). Tokens already issued are left # alone and live until they expire; refresh tokens exist only with offline_access, # which OIDC Core §11 defines as access while the End-User is not logged in. # # Usage: pwsh -File demo_me_sessions.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $SCOPE = "openid profile identity:account" $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } function ConvertTo-Base64Url([byte[]]$bytes) { [Convert]::ToBase64String($bytes).TrimEnd('=').Replace('+','-').Replace('/','_') } function Get-JwtPayload([string]$jwt) { $p = $jwt.Split('.')[1].Replace('-','+').Replace('_','/') switch ($p.Length % 4) { 2 { $p += '==' } 3 { $p += '=' } } [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($p)) | ConvertFrom-Json } # Query parameters of the Location header of an /connect/authorize answer (no redirects followed). function Invoke-Authorize { param($Session, [hashtable]$Body) $resp = $null try { $resp = Invoke-WebRequest -Method Post "$BASE/connect/authorize" -WebSession $Session ` -ContentType "application/x-www-form-urlencoded" -Body $Body -MaximumRedirection 0 -ErrorAction Stop } catch { $resp = $_.Exception.Response } $location = if ($resp -is [System.Net.Http.HttpResponseMessage]) { [string]$resp.Headers.Location } else { [string]$resp.Headers["Location"] } if (-not $location) { throw "no Location header on /connect/authorize response" } $kv = @{ location = $location } $u = [uri]::new([uri]$BASE, $location) foreach ($pair in $u.Query.TrimStart('?').Split('&')) { $i = $pair.IndexOf('=') if ($i -gt 0) { $kv[$pair.Substring(0,$i)] = [uri]::UnescapeDataString($pair.Substring($i+1)) } } $kv } # One device: its own cookie jar, POST /login, then code + PKCE for a session-bound token. function New-Device { param([int]$N) $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession try { Invoke-WebRequest -Method Post "$BASE/login" -WebSession $session ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ username = $user; password = $pwd } -MaximumRedirection 0 -ErrorAction Stop | Out-Null } catch { if ($_.Exception.Response.StatusCode.value__ -notin 200,302) { throw } } if ($session.Cookies.GetCookies("$BASE").Count -lt 1) { throw "no session cookie was set by /login" } $verifierBytes = New-Object byte[] 32 [System.Security.Cryptography.RandomNumberGenerator]::Fill($verifierBytes) $verifier = ConvertTo-Base64Url $verifierBytes $challenge = ConvertTo-Base64Url ([System.Security.Cryptography.SHA256]::HashData([Text.Encoding]::ASCII.GetBytes($verifier))) $kv = Invoke-Authorize $session @{ response_type = "code"; client_id = $reg.client_id; redirect_uri = $REDIRECT_CB; scope = $SCOPE code_challenge = $challenge; code_challenge_method = "S256" state = "dev$N-$([Guid]::NewGuid().ToString('N'))"; nonce = [Guid]::NewGuid().ToString('N') } if (-not $kv.code) { throw "authorize did not return a code (got: $($kv.location))" } $tok = Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "authorization_code"; client_id = $reg.client_id; client_secret = $reg.client_secret redirect_uri = $REDIRECT_CB; code = $kv.code; code_verifier = $verifier } $sid = [string](Get-JwtPayload $tok.id_token).sid if (-not $sid) { throw "id_token of device #$N has no sid claim" } Write-Host " device #$N session id (sid): $sid" [pscustomobject]@{ N = $N; Session = $session; Sid = $sid; Bearer = @{ Authorization = "Bearer $($tok.access_token)" } } } # Silent sign-in with the device's cookie: a code while its session lives, login_required after a revoke. function Test-SilentSignIn { param($Device) $verifierBytes = New-Object byte[] 32 [System.Security.Cryptography.RandomNumberGenerator]::Fill($verifierBytes) $challenge = ConvertTo-Base64Url ([System.Security.Cryptography.SHA256]::HashData([Text.Encoding]::ASCII.GetBytes((ConvertTo-Base64Url $verifierBytes)))) $kv = Invoke-Authorize $Device.Session @{ response_type = "code"; client_id = $reg.client_id; redirect_uri = $REDIRECT_CB; scope = $SCOPE prompt = "none"; state = "silent-$([Guid]::NewGuid().ToString('N'))"; nonce = [Guid]::NewGuid().ToString('N') code_challenge = $challenge; code_challenge_method = "S256" } if ($kv.code) { return "code" } if ($kv.error) { return $kv.error } throw "unexpected authorize answer: $($kv.location)" } function Get-MySessionIds { param([hashtable]$Bearer) $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/me/sessions" -Headers $Bearer $items = if ($null -eq $r) { @() } elseif ($r -is [System.Array]) { $r } elseif ($r.items) { $r.items } else { @($r) } @($items | ForEach-Object { [string]$_.sessionId } | Where-Object { $_ } | Sort-Object) } function Assert-SessionIds { param([string[]]$Actual, [string[]]$Expected, [string]$What) $a = (@($Actual) | Sort-Object) -join ',' $e = (@($Expected) | Sort-Object) -join ',' if ($a -ne $e) { throw "$What : expected sessions [$e], listed [$a]" } Write-Host " ✓ $What : [$a]" -ForegroundColor Green } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR: authorization_code client with identity:account so /me/sessions is authorized. $reg = Measure-Step "1. DCR /connect/register (authorization_code + identity:account)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "sess-demo" redirect_uris = @($REDIRECT_CB) grant_types = @("authorization_code") scope = $SCOPE } | ConvertTo-Json) } # 2) Seed user. $user = "sess_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" Measure-Step "2. account/register" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = "$user@example.com" password = $pwd displayName = $user } | ConvertTo-Json) } | Out-Null # 3) Three devices, three OP sessions. $dev = @{} foreach ($i in 1..3) { $dev[$i] = Measure-Step "3.$i device #$i : POST /login + authorization_code (PKCE)" { New-Device $i } } if (@($dev.Values.Sid | Sort-Object -Unique).Count -ne 3) { throw "the three logins did not open three distinct sessions" } # 4) GET /me/sessions lists exactly the three sessions. Measure-Step "4. GET /me/sessions lists the three sessions" { Assert-SessionIds (Get-MySessionIds $dev[3].Bearer) @($dev[1].Sid, $dev[2].Sid, $dev[3].Sid) "listed" } | Out-Null # 5) DELETE /{id}: device #1's session ends; its cookie no longer signs in silently. Measure-Step "5. DELETE /me/sessions/ (device #1)" { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/me/sessions/$($dev[1].Sid)" -Headers $dev[3].Bearer | Out-Null Assert-SessionIds (Get-MySessionIds $dev[3].Bearer) @($dev[2].Sid, $dev[3].Sid) "after revoking device #1" $r = Test-SilentSignIn $dev[1] if ($r -ne "login_required") { throw "device #1 silent sign-in after revoke: expected login_required, got $r" } Write-Host " ✓ device #1 prompt=none -> login_required" -ForegroundColor Green $r = Test-SilentSignIn $dev[2] if ($r -ne "code") { throw "device #2 silent sign-in while its session lives: expected a code, got $r" } Write-Host " ✓ device #2 prompt=none -> code (its session is untouched)" -ForegroundColor Green } | Out-Null # 6) DELETE /others: everything but the caller's own session (the sid of its token) ends. Measure-Step "6. DELETE /me/sessions/others (from device #3)" { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/me/sessions/others" -Headers $dev[3].Bearer | Out-Null Assert-SessionIds (Get-MySessionIds $dev[3].Bearer) @($dev[3].Sid) "after /others" $r = Test-SilentSignIn $dev[2] if ($r -ne "login_required") { throw "device #2 silent sign-in after /others: expected login_required, got $r" } Write-Host " ✓ device #2 prompt=none -> login_required" -ForegroundColor Green } | Out-Null # 7) DELETE /current: the caller's own session ends. Measure-Step "7. DELETE /me/sessions/current (device #3)" { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/me/sessions/current" -Headers $dev[3].Bearer | Out-Null $r = Test-SilentSignIn $dev[3] if ($r -ne "login_required") { throw "device #3 silent sign-in after /current: expected login_required, got $r" } Write-Host " ✓ device #3 prompt=none -> login_required" -ForegroundColor Green # The access token was issued before the revoke and lives until it expires (see the header). Assert-SessionIds (Get-MySessionIds $dev[3].Bearer) @() "after /current, with the token issued before it" } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan