@sso-id/cli 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/sso-id.mjs +128 -7
- package/package.json +3 -2
- package/templates/angular-spa/package.json +19 -0
- package/templates/angular-spa/src/app/app.component.ts +63 -0
- package/templates/angular-spa/src/app/app.config.ts +16 -0
- package/templates/angular-spa/src/environments/environment.ts +7 -0
- package/templates/dotnet-api/Program.cs +121 -0
- package/templates/dotnet-api/SsoIdStarter.csproj +12 -0
- package/templates/dotnet-api/appsettings.json +14 -0
- package/templates/express-api/.env.example +12 -0
- package/templates/express-api/README.md +8 -0
- package/templates/express-api/package.json +18 -0
- package/templates/express-api/src/server.mjs +182 -0
- package/templates/go-gin/.env.example +7 -0
- package/templates/go-gin/go.mod +6 -0
- package/templates/go-gin/main.go +112 -0
- package/templates/mobile-react-native/.env.example +5 -0
- package/templates/mobile-react-native/App.tsx +45 -0
- package/templates/mobile-react-native/package.json +11 -0
- package/templates/nextjs/.env.example +19 -0
- package/templates/nextjs/README.md +18 -0
- package/templates/nextjs/next.config.mjs +4 -0
- package/templates/nextjs/package.json +27 -0
- package/templates/nextjs/src/app/api/auth/[...ssoid]/route.ts +10 -0
- package/templates/nextjs/src/app/api/management/[resource]/route.ts +64 -0
- package/templates/nextjs/src/app/api/scim/sync/route.ts +60 -0
- package/templates/nextjs/src/app/api/scim/v2/Groups/[id]/route.ts +58 -0
- package/templates/nextjs/src/app/api/scim/v2/Groups/route.ts +44 -0
- package/templates/nextjs/src/app/api/scim/v2/Users/[id]/route.ts +89 -0
- package/templates/nextjs/src/app/api/scim/v2/Users/route.ts +44 -0
- package/templates/nextjs/src/app/layout.tsx +18 -0
- package/templates/nextjs/src/app/page.tsx +164 -0
- package/templates/nextjs/src/app/providers.tsx +16 -0
- package/templates/nextjs/src/lib/scim-auth.ts +12 -0
- package/templates/nextjs/src/lib/sso.ts +39 -0
- package/templates/nextjs/tsconfig.json +24 -0
- package/templates/php-laravel/.env.example +6 -0
- package/templates/php-laravel/composer.json +9 -0
- package/templates/php-laravel/public/index.php +34 -0
- package/templates/python-fastapi/.env.example +7 -0
- package/templates/python-fastapi/main.py +155 -0
- package/templates/python-fastapi/requirements.txt +6 -0
- package/templates/react-spa/.env.example +5 -0
- package/templates/react-spa/package.json +25 -0
- package/templates/react-spa/src/App.tsx +67 -0
- package/templates/react-spa/src/main.tsx +17 -0
- package/templates/vue-spa/.env.example +5 -0
- package/templates/vue-spa/package.json +20 -0
- package/templates/vue-spa/src/App.vue +57 -0
- package/templates/vue-spa/src/main.ts +14 -0
package/bin/sso-id.mjs
CHANGED
|
@@ -1,4 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { cpSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
7
|
+
|
|
8
|
+
export const AVAILABLE_TEMPLATES = [
|
|
9
|
+
'nextjs',
|
|
10
|
+
'react-spa',
|
|
11
|
+
'angular-spa',
|
|
12
|
+
'vue-spa',
|
|
13
|
+
'express-api',
|
|
14
|
+
'dotnet-api',
|
|
15
|
+
'python-fastapi',
|
|
16
|
+
'go-gin',
|
|
17
|
+
'php-laravel',
|
|
18
|
+
'mobile-react-native',
|
|
19
|
+
];
|
|
2
20
|
|
|
3
21
|
export function decodeJwt(token) {
|
|
4
22
|
const parts = token.split('.');
|
|
@@ -10,24 +28,128 @@ export function decodeJwt(token) {
|
|
|
10
28
|
return { header, payload };
|
|
11
29
|
}
|
|
12
30
|
|
|
13
|
-
export function generateEnvTemplate({ domain, clientId, redirectUri }) {
|
|
14
|
-
|
|
31
|
+
export function generateEnvTemplate({ domain, clientId, clientSecret, redirectUri, scimToken }) {
|
|
32
|
+
const lines = [
|
|
15
33
|
`SSO_ID_DOMAIN=${domain}`,
|
|
16
34
|
`SSO_ID_CLIENT_ID=${clientId}`,
|
|
17
35
|
`SSO_ID_REDIRECT_URI=${redirectUri || 'http://localhost:3000/callback'}`,
|
|
18
|
-
]
|
|
36
|
+
];
|
|
37
|
+
if (clientSecret) lines.push(`SSO_ID_CLIENT_SECRET=${clientSecret}`);
|
|
38
|
+
if (scimToken) lines.push(`SSO_ID_SCIM_BEARER_TOKEN=${scimToken}`);
|
|
39
|
+
return lines.join('\n');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function parseFlags(argv) {
|
|
43
|
+
const flags = {};
|
|
44
|
+
const positional = [];
|
|
45
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
46
|
+
const arg = argv[i];
|
|
47
|
+
if (arg.startsWith('--')) {
|
|
48
|
+
const key = arg.slice(2);
|
|
49
|
+
const next = argv[i + 1];
|
|
50
|
+
if (next && !next.startsWith('--')) {
|
|
51
|
+
flags[key] = next;
|
|
52
|
+
i += 1;
|
|
53
|
+
} else {
|
|
54
|
+
flags[key] = 'true';
|
|
55
|
+
}
|
|
56
|
+
} else {
|
|
57
|
+
positional.push(arg);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return { flags, positional };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function applyEnvOverrides(templateEnv, overrides) {
|
|
64
|
+
let content = templateEnv;
|
|
65
|
+
const replacements = {
|
|
66
|
+
SSO_ID_DOMAIN: overrides.domain,
|
|
67
|
+
NEXT_PUBLIC_SSO_ID_DOMAIN: overrides.domain,
|
|
68
|
+
VITE_SSO_ID_DOMAIN: overrides.domain,
|
|
69
|
+
SSO_ID_CLIENT_ID: overrides.clientId,
|
|
70
|
+
NEXT_PUBLIC_SSO_ID_CLIENT_ID: overrides.clientId,
|
|
71
|
+
VITE_SSO_ID_CLIENT_ID: overrides.clientId,
|
|
72
|
+
SSO_ID_CLIENT_SECRET: overrides.clientSecret,
|
|
73
|
+
SSO_ID_M2M_CLIENT_ID: overrides.clientId,
|
|
74
|
+
SSO_ID_M2M_CLIENT_SECRET: overrides.clientSecret,
|
|
75
|
+
SSO_ID_SCIM_BEARER_TOKEN: overrides.scimToken,
|
|
76
|
+
};
|
|
77
|
+
for (const [key, val] of Object.entries(replacements)) {
|
|
78
|
+
if (!val) continue;
|
|
79
|
+
const regex = new RegExp(`^${key}=.*$`, 'gm');
|
|
80
|
+
if (regex.test(content)) {
|
|
81
|
+
content = content.replace(regex, `${key}=${val}`);
|
|
82
|
+
} else {
|
|
83
|
+
content += `\n${key}=${val}`;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return `${content.trimEnd()}\n`;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function scaffoldTemplate(templateName, targetDir, overrides = {}) {
|
|
90
|
+
if (!AVAILABLE_TEMPLATES.includes(templateName)) {
|
|
91
|
+
throw new Error(`Unknown template "${templateName}". Available: ${AVAILABLE_TEMPLATES.join(', ')}`);
|
|
92
|
+
}
|
|
93
|
+
const bundledTemplates = resolve(__dirname, '..', 'templates');
|
|
94
|
+
const workspaceTemplates = resolve(__dirname, '..', '..', '..', 'templates');
|
|
95
|
+
const templatesRoot = existsSync(bundledTemplates) ? bundledTemplates : workspaceTemplates;
|
|
96
|
+
const sourceDir = join(templatesRoot, templateName);
|
|
97
|
+
const destDir = resolve(targetDir || `sso-id-${templateName}`);
|
|
98
|
+
mkdirSync(destDir, { recursive: true });
|
|
99
|
+
|
|
100
|
+
if (existsSync(sourceDir)) {
|
|
101
|
+
cpSync(sourceDir, destDir, { recursive: true });
|
|
102
|
+
const envExamplePath = join(destDir, '.env.example');
|
|
103
|
+
const baseEnv = existsSync(envExamplePath)
|
|
104
|
+
? readFileSync(envExamplePath, 'utf8')
|
|
105
|
+
: generateEnvTemplate({ domain: 'acme.sso.id', clientId: 'YOUR_CLIENT_ID', ...overrides });
|
|
106
|
+
writeFileSync(join(destDir, '.env'), applyEnvOverrides(baseEnv, overrides), 'utf8');
|
|
107
|
+
} else {
|
|
108
|
+
writeFileSync(
|
|
109
|
+
join(destDir, '.env'),
|
|
110
|
+
generateEnvTemplate({ domain: overrides.domain || 'acme.sso.id', clientId: overrides.clientId || 'YOUR_CLIENT_ID', ...overrides }),
|
|
111
|
+
'utf8',
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
return destDir;
|
|
19
115
|
}
|
|
20
116
|
|
|
21
117
|
async function main() {
|
|
22
|
-
const
|
|
118
|
+
const { flags, positional } = parseFlags(process.argv.slice(2));
|
|
119
|
+
const [cmd, arg1, arg2] = positional;
|
|
120
|
+
|
|
23
121
|
if (!cmd || cmd === '--help' || cmd === '-h') {
|
|
24
|
-
console.log(
|
|
122
|
+
console.log(
|
|
123
|
+
'Usage: sso-id <command>\n\nCommands:\n' +
|
|
124
|
+
' list-templates List pre-built SSO.ID starter templates\n' +
|
|
125
|
+
' create <template> [dir] [--domain ...] Scaffold a pre-configured template with SCIM & Management API\n' +
|
|
126
|
+
' init <domain> <clientId> Print .env starter config\n' +
|
|
127
|
+
' decode-token <jwt> Decode JWT header & payload\n' +
|
|
128
|
+
' test-discovery <domain> Fetch OIDC discovery metadata',
|
|
129
|
+
);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (cmd === 'list-templates') {
|
|
134
|
+
console.log(AVAILABLE_TEMPLATES.join('\n'));
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (cmd === 'create') {
|
|
139
|
+
if (!arg1) throw new Error(`Specify a template name. Available: ${AVAILABLE_TEMPLATES.join(', ')}`);
|
|
140
|
+
const dest = scaffoldTemplate(arg1, arg2, {
|
|
141
|
+
domain: flags.domain,
|
|
142
|
+
clientId: flags['client-id'],
|
|
143
|
+
clientSecret: flags['client-secret'],
|
|
144
|
+
scimToken: flags['scim-token'],
|
|
145
|
+
});
|
|
146
|
+
console.log(`Created SSO.ID "${arg1}" starter at: ${dest}`);
|
|
25
147
|
return;
|
|
26
148
|
}
|
|
27
149
|
|
|
28
150
|
if (cmd === 'init') {
|
|
29
151
|
const domain = arg1 || 'acme.sso.id';
|
|
30
|
-
const clientId =
|
|
152
|
+
const clientId = arg2 || 'YOUR_CLIENT_ID';
|
|
31
153
|
console.log(generateEnvTemplate({ domain, clientId }));
|
|
32
154
|
return;
|
|
33
155
|
}
|
|
@@ -57,4 +179,3 @@ if (isDirectRun) {
|
|
|
57
179
|
process.exit(1);
|
|
58
180
|
});
|
|
59
181
|
}
|
|
60
|
-
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sso-id/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Official SSO.ID Developer CLI (init, decode-token, test-discovery)",
|
|
6
6
|
"bin": {
|
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
"access": "public"
|
|
25
25
|
},
|
|
26
26
|
"files": [
|
|
27
|
-
"bin"
|
|
27
|
+
"bin",
|
|
28
|
+
"templates"
|
|
28
29
|
]
|
|
29
30
|
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "sso-id-angular-template",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"scripts": {
|
|
6
|
+
"start": "ng serve",
|
|
7
|
+
"build": "ng build"
|
|
8
|
+
},
|
|
9
|
+
"dependencies": {
|
|
10
|
+
"@angular/common": "^18.2.0",
|
|
11
|
+
"@angular/core": "^18.2.0",
|
|
12
|
+
"@angular/forms": "^18.2.0",
|
|
13
|
+
"@angular/platform-browser": "^18.2.0",
|
|
14
|
+
"@angular/router": "^18.2.0",
|
|
15
|
+
"@sso-id/angular": "^0.1.0",
|
|
16
|
+
"rxjs": "^7.8.1"
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { Component, OnInit, inject } from '@angular/core';
|
|
2
|
+
import { CommonModule } from '@angular/common';
|
|
3
|
+
import { FormsModule } from '@angular/forms';
|
|
4
|
+
import { HttpClient } from '@angular/common/http';
|
|
5
|
+
import { SsoIdService } from '@sso-id/angular';
|
|
6
|
+
import { environment } from '../environments/environment';
|
|
7
|
+
|
|
8
|
+
@Component({
|
|
9
|
+
selector: 'app-root',
|
|
10
|
+
standalone: true,
|
|
11
|
+
imports: [CommonModule, FormsModule],
|
|
12
|
+
template: `
|
|
13
|
+
<main style="max-width:960px;margin:32px auto;font-family:system-ui,sans-serif;padding:16px">
|
|
14
|
+
<header style="display:flex;justify-content:space-between;align-items:center;margin-bottom:24px">
|
|
15
|
+
<h1>SSO.ID Angular Starter</h1>
|
|
16
|
+
<button *ngIf="!(sso.isAuthenticated$ | async)" (click)="sso.loginWithRedirect()">Sign In with SSO.ID</button>
|
|
17
|
+
<button *ngIf="sso.isAuthenticated$ | async" (click)="sso.logout()">Sign Out</button>
|
|
18
|
+
</header>
|
|
19
|
+
<section *ngIf="sso.isAuthenticated$ | async">
|
|
20
|
+
<div style="display:flex;gap:8px;margin-bottom:16px">
|
|
21
|
+
<button *ngFor="let t of tabs" (click)="selectTab(t)">{{ t }}</button>
|
|
22
|
+
</div>
|
|
23
|
+
<form (ngSubmit)="create()" style="display:flex;gap:8px;margin-bottom:16px">
|
|
24
|
+
<input [(ngModel)]="name" name="name" placeholder="Name or email" required />
|
|
25
|
+
<button type="submit">Create</button>
|
|
26
|
+
</form>
|
|
27
|
+
<pre style="background:#0f172a;color:#e2e8f0;padding:16px;border-radius:8px">{{ data | json }}</pre>
|
|
28
|
+
</section>
|
|
29
|
+
</main>
|
|
30
|
+
`,
|
|
31
|
+
})
|
|
32
|
+
export class AppComponent implements OnInit {
|
|
33
|
+
sso = inject(SsoIdService);
|
|
34
|
+
private http = inject(HttpClient);
|
|
35
|
+
tabs = ['organizations', 'organization-units', 'users', 'groups', 'scim'] as const;
|
|
36
|
+
tab: (typeof this.tabs)[number] = 'organizations';
|
|
37
|
+
name = '';
|
|
38
|
+
data: unknown = null;
|
|
39
|
+
|
|
40
|
+
ngOnInit(): void {
|
|
41
|
+
this.load();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
selectTab(tab: (typeof this.tabs)[number]): void {
|
|
45
|
+
this.tab = tab;
|
|
46
|
+
this.load();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
load(): void {
|
|
50
|
+
const path = this.tab === 'scim' ? '/api/scim/events' : `/api/${this.tab}`;
|
|
51
|
+
this.http.get(`${environment.apiBaseUrl}${path}`).subscribe((res) => (this.data = res));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
create(): void {
|
|
55
|
+
const path = this.tab === 'scim' ? '/api/scim/push-user' : `/api/${this.tab}`;
|
|
56
|
+
const body = this.tab === 'users' || this.tab === 'scim' ? { email: this.name, userName: this.name, displayName: this.name } : { name: this.name };
|
|
57
|
+
this.http.post(`${environment.apiBaseUrl}${path}`, body).subscribe(() => {
|
|
58
|
+
this.name = '';
|
|
59
|
+
this.load();
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { ApplicationConfig } from '@angular/core';
|
|
2
|
+
import { provideHttpClient, withInterceptors } from '@angular/common/http';
|
|
3
|
+
import { provideSsoId, ssoIdHttpInterceptor } from '@sso-id/angular';
|
|
4
|
+
import { environment } from '../environments/environment';
|
|
5
|
+
|
|
6
|
+
export const appConfig: ApplicationConfig = {
|
|
7
|
+
providers: [
|
|
8
|
+
provideHttpClient(withInterceptors([ssoIdHttpInterceptor])),
|
|
9
|
+
provideSsoId({
|
|
10
|
+
domain: environment.ssoIdDomain,
|
|
11
|
+
clientId: environment.ssoIdClientId,
|
|
12
|
+
redirectUri: environment.ssoIdRedirectUri,
|
|
13
|
+
}),
|
|
14
|
+
],
|
|
15
|
+
};
|
|
16
|
+
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
using System.Collections.Concurrent;
|
|
2
|
+
using System.Security.Cryptography;
|
|
3
|
+
using System.Text;
|
|
4
|
+
using System.Text.Json;
|
|
5
|
+
using Microsoft.AspNetCore.Authorization;
|
|
6
|
+
using SsoId.AspNetCore;
|
|
7
|
+
using SsoId.ManagementApi;
|
|
8
|
+
|
|
9
|
+
var builder = WebApplication.CreateBuilder(args);
|
|
10
|
+
|
|
11
|
+
var domain = builder.Configuration["SsoId:Domain"] ?? "acme.sso.id";
|
|
12
|
+
var audience = builder.Configuration["SsoId:Audience"] ?? "https://api.acme.com";
|
|
13
|
+
var scimToken = builder.Configuration["Scim:BearerToken"] ?? "";
|
|
14
|
+
|
|
15
|
+
builder.Services.AddSsoIdApi(opts =>
|
|
16
|
+
{
|
|
17
|
+
opts.Domain = domain;
|
|
18
|
+
opts.Audience = audience;
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
builder.Services.AddSingleton(new SsoManagementOptions
|
|
22
|
+
{
|
|
23
|
+
Domain = domain,
|
|
24
|
+
ClientId = builder.Configuration["SsoId:ClientId"] ?? "",
|
|
25
|
+
ClientSecret = builder.Configuration["SsoId:ClientSecret"] ?? "",
|
|
26
|
+
ApiBaseUrl = builder.Configuration["SsoId:ApiBaseUrl"] ?? "https://api.sso.id",
|
|
27
|
+
});
|
|
28
|
+
builder.Services.AddHttpClient<ISsoManagementClient, SsoManagementClient>();
|
|
29
|
+
builder.Services.AddCors(o => o.AddDefaultPolicy(p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
|
|
30
|
+
|
|
31
|
+
var app = builder.Build();
|
|
32
|
+
app.UseCors();
|
|
33
|
+
app.UseAuthentication();
|
|
34
|
+
app.UseAuthorization();
|
|
35
|
+
|
|
36
|
+
var scimUsers = new ConcurrentDictionary<string, JsonElement>();
|
|
37
|
+
var scimGroups = new ConcurrentDictionary<string, JsonElement>();
|
|
38
|
+
var scimEvents = new ConcurrentQueue<object>();
|
|
39
|
+
|
|
40
|
+
bool ValidScimToken(HttpRequest req)
|
|
41
|
+
{
|
|
42
|
+
var header = req.Headers.Authorization.ToString();
|
|
43
|
+
if (!header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) || string.IsNullOrEmpty(scimToken))
|
|
44
|
+
return false;
|
|
45
|
+
var a = Encoding.UTF8.GetBytes(header["Bearer ".Length..].Trim());
|
|
46
|
+
var b = Encoding.UTF8.GetBytes(scimToken);
|
|
47
|
+
return a.Length == b.Length && CryptographicOperations.FixedTimeEquals(a, b);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Management API routes (Organizations, OUs, Users, Groups)
|
|
51
|
+
app.MapGet("/api/organizations", [Authorize] (ISsoManagementClient mgmt, CancellationToken ct) => mgmt.ListOrganizationsAsync(ct));
|
|
52
|
+
app.MapPost("/api/organizations", [Authorize] (JsonElement body, ISsoManagementClient mgmt, CancellationToken ct) => mgmt.CreateOrganizationAsync(body, ct));
|
|
53
|
+
|
|
54
|
+
app.MapGet("/api/organization-units", [Authorize] (string? organizationId, ISsoManagementClient mgmt, CancellationToken ct) => mgmt.ListOrganizationUnitsAsync(organizationId, ct));
|
|
55
|
+
app.MapPost("/api/organization-units", [Authorize] (JsonElement body, ISsoManagementClient mgmt, CancellationToken ct) => mgmt.CreateOrganizationUnitAsync(body, ct));
|
|
56
|
+
|
|
57
|
+
app.MapGet("/api/users", [Authorize] (ISsoManagementClient mgmt, CancellationToken ct) => mgmt.ListUsersAsync(1, 50, ct));
|
|
58
|
+
app.MapPost("/api/users", [Authorize] (JsonElement body, ISsoManagementClient mgmt, CancellationToken ct) => mgmt.CreateUserAsync(body, ct));
|
|
59
|
+
|
|
60
|
+
app.MapGet("/api/groups", [Authorize] (ISsoManagementClient mgmt, CancellationToken ct) => mgmt.ListGroupsAsync(ct));
|
|
61
|
+
app.MapPost("/api/groups", [Authorize] (JsonElement body, ISsoManagementClient mgmt, CancellationToken ct) => mgmt.CreateGroupAsync(body, ct));
|
|
62
|
+
|
|
63
|
+
// Real-Time SCIM 2.0 Receiver
|
|
64
|
+
app.MapGet("/scim/v2/Users", (HttpRequest req) =>
|
|
65
|
+
{
|
|
66
|
+
if (!ValidScimToken(req)) return Results.Unauthorized();
|
|
67
|
+
var list = scimUsers.Values.ToList();
|
|
68
|
+
return Results.Ok(new
|
|
69
|
+
{
|
|
70
|
+
schemas = new[] { "urn:ietf:params:scim:api:messages:2.0:ListResponse" },
|
|
71
|
+
totalResults = list.Count,
|
|
72
|
+
startIndex = 1,
|
|
73
|
+
itemsPerPage = list.Count,
|
|
74
|
+
Resources = list,
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
app.MapPost("/scim/v2/Users", (HttpRequest req, JsonElement body) =>
|
|
79
|
+
{
|
|
80
|
+
if (!ValidScimToken(req)) return Results.Unauthorized();
|
|
81
|
+
var id = body.TryGetProperty("id", out var idProp) ? idProp.GetString() ?? Guid.NewGuid().ToString() : Guid.NewGuid().ToString();
|
|
82
|
+
scimUsers[id] = body;
|
|
83
|
+
scimEvents.Enqueue(new { type = "User", op = "CREATE", id, at = DateTimeOffset.UtcNow });
|
|
84
|
+
return Results.Created($"/scim/v2/Users/{id}", body);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
app.MapDelete("/scim/v2/Users/{id}", (HttpRequest req, string id) =>
|
|
88
|
+
{
|
|
89
|
+
if (!ValidScimToken(req)) return Results.Unauthorized();
|
|
90
|
+
scimUsers.TryRemove(id, out _);
|
|
91
|
+
scimEvents.Enqueue(new { type = "User", op = "DELETE", id, at = DateTimeOffset.UtcNow });
|
|
92
|
+
return Results.NoContent();
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
app.MapGet("/scim/v2/Groups", (HttpRequest req) =>
|
|
96
|
+
{
|
|
97
|
+
if (!ValidScimToken(req)) return Results.Unauthorized();
|
|
98
|
+
var list = scimGroups.Values.ToList();
|
|
99
|
+
return Results.Ok(new
|
|
100
|
+
{
|
|
101
|
+
schemas = new[] { "urn:ietf:params:scim:api:messages:2.0:ListResponse" },
|
|
102
|
+
totalResults = list.Count,
|
|
103
|
+
startIndex = 1,
|
|
104
|
+
itemsPerPage = list.Count,
|
|
105
|
+
Resources = list,
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
app.MapPost("/scim/v2/Groups", (HttpRequest req, JsonElement body) =>
|
|
110
|
+
{
|
|
111
|
+
if (!ValidScimToken(req)) return Results.Unauthorized();
|
|
112
|
+
var id = body.TryGetProperty("id", out var idProp) ? idProp.GetString() ?? Guid.NewGuid().ToString() : Guid.NewGuid().ToString();
|
|
113
|
+
scimGroups[id] = body;
|
|
114
|
+
scimEvents.Enqueue(new { type = "Group", op = "CREATE", id, at = DateTimeOffset.UtcNow });
|
|
115
|
+
return Results.Created($"/scim/v2/Groups/{id}", body);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
app.MapGet("/api/scim/events", [Authorize] () => Results.Ok(new { users = scimUsers.Values, groups = scimGroups.Values, events = scimEvents }));
|
|
119
|
+
|
|
120
|
+
app.Run();
|
|
121
|
+
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
<Project Sdk="Microsoft.NET.Sdk.Web">
|
|
2
|
+
<PropertyGroup>
|
|
3
|
+
<TargetFramework>net8.0</TargetFramework>
|
|
4
|
+
<Nullable>enable</Nullable>
|
|
5
|
+
<ImplicitUsings>enable</ImplicitUsings>
|
|
6
|
+
</PropertyGroup>
|
|
7
|
+
<ItemGroup>
|
|
8
|
+
<PackageReference Include="SsoId.AspNetCore" Version="0.1.0" />
|
|
9
|
+
<PackageReference Include="SsoId.ManagementApi" Version="0.1.0" />
|
|
10
|
+
</ItemGroup>
|
|
11
|
+
</Project>
|
|
12
|
+
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"SsoId": {
|
|
3
|
+
"Domain": "acme.sso.id",
|
|
4
|
+
"Audience": "https://api.acme.com",
|
|
5
|
+
"ClientId": "YOUR_M2M_CLIENT_ID",
|
|
6
|
+
"ClientSecret": "YOUR_M2M_CLIENT_SECRET",
|
|
7
|
+
"ApiBaseUrl": "https://api.sso.id"
|
|
8
|
+
},
|
|
9
|
+
"Scim": {
|
|
10
|
+
"BearerToken": "REPLACE_WITH_STRONG_SCIM_TOKEN",
|
|
11
|
+
"ConnectionId": ""
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
PORT=4000
|
|
2
|
+
SSO_ID_DOMAIN=acme.sso.id
|
|
3
|
+
SSO_ID_CLIENT_ID=YOUR_CLIENT_ID
|
|
4
|
+
SSO_ID_CLIENT_SECRET=YOUR_CLIENT_SECRET
|
|
5
|
+
SSO_ID_BASE_URL=http://localhost:4000
|
|
6
|
+
SSO_ID_SESSION_SECRET=REPLACE_WITH_LONG_RANDOM_SECRET
|
|
7
|
+
SSO_ID_API_BASE_URL=https://api.sso.id
|
|
8
|
+
SSO_ID_AUDIENCE=
|
|
9
|
+
SSO_ID_SCIM_BEARER_TOKEN=REPLACE_WITH_STRONG_SCIM_TOKEN
|
|
10
|
+
SSO_ID_SCIM_CONNECTION_ID=
|
|
11
|
+
CORS_ORIGIN=http://localhost:5173
|
|
12
|
+
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# SSO.ID Express + SCIM 2.0 + Management API Template
|
|
2
|
+
|
|
3
|
+
Pre-configured Express backend using `@sso-id/express` and `@sso-id/node`:
|
|
4
|
+
- OIDC login/callback/logout (`/login`, `/callback`, `/logout`)
|
|
5
|
+
- Bearer JWT + session verification for SPAs & Mobile apps
|
|
6
|
+
- Organizations, Organization Units, Users, and Groups Management API routes
|
|
7
|
+
- Real-Time SCIM 2.0 receiver (`/scim/v2/Users`, `/scim/v2/Groups`) and outbound SCIM push (`/api/scim/push-user`)
|
|
8
|
+
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "sso-id-express-template",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"dev": "node --watch src/server.mjs",
|
|
8
|
+
"start": "node src/server.mjs"
|
|
9
|
+
},
|
|
10
|
+
"dependencies": {
|
|
11
|
+
"@sso-id/express": "^0.1.0",
|
|
12
|
+
"@sso-id/node": "^0.2.0",
|
|
13
|
+
"cors": "^2.8.5",
|
|
14
|
+
"dotenv": "^16.4.5",
|
|
15
|
+
"express": "^4.21.0"
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import 'dotenv/config';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import express from 'express';
|
|
4
|
+
import cors from 'cors';
|
|
5
|
+
import { auth, requiresAuth } from '@sso-id/express';
|
|
6
|
+
import {
|
|
7
|
+
ManagementClient,
|
|
8
|
+
verifyAccessToken,
|
|
9
|
+
verifyScimBearerToken,
|
|
10
|
+
formatScimListResponse,
|
|
11
|
+
formatScimError,
|
|
12
|
+
SCIM_CORE_USER_SCHEMA,
|
|
13
|
+
SCIM_CORE_GROUP_SCHEMA,
|
|
14
|
+
} from '@sso-id/node';
|
|
15
|
+
|
|
16
|
+
const app = express();
|
|
17
|
+
app.use(cors({ origin: process.env.CORS_ORIGIN || true, credentials: true }));
|
|
18
|
+
app.use(express.json({ type: ['application/json', 'application/scim+json'] }));
|
|
19
|
+
|
|
20
|
+
const mgmt = new ManagementClient({
|
|
21
|
+
domain: process.env.SSO_ID_DOMAIN || 'acme.sso.id',
|
|
22
|
+
clientId: process.env.SSO_ID_CLIENT_ID || '',
|
|
23
|
+
clientSecret: process.env.SSO_ID_CLIENT_SECRET || '',
|
|
24
|
+
apiBaseUrl: process.env.SSO_ID_API_BASE_URL || 'https://api.sso.id',
|
|
25
|
+
audience: process.env.SSO_ID_AUDIENCE || undefined,
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
// 1. OIDC Session Auth (@sso-id/express)
|
|
29
|
+
app.use(
|
|
30
|
+
auth({
|
|
31
|
+
domain: process.env.SSO_ID_DOMAIN || 'acme.sso.id',
|
|
32
|
+
clientId: process.env.SSO_ID_CLIENT_ID || '',
|
|
33
|
+
clientSecret: process.env.SSO_ID_CLIENT_SECRET || '',
|
|
34
|
+
baseURL: process.env.SSO_ID_BASE_URL || 'http://localhost:4000',
|
|
35
|
+
secret: process.env.SSO_ID_SESSION_SECRET || 'dev-secret-change-me',
|
|
36
|
+
}),
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
// Bearer JWT guard for SPA / Mobile callers
|
|
40
|
+
async function requireBearerOrSession(req, res, next) {
|
|
41
|
+
if (req.oidc?.isAuthenticated()) return next();
|
|
42
|
+
const header = req.headers.authorization || '';
|
|
43
|
+
const token = header.startsWith('Bearer ') ? header.slice(7) : '';
|
|
44
|
+
if (!token) return res.status(401).json({ error: 'Unauthorized' });
|
|
45
|
+
try {
|
|
46
|
+
req.user = await verifyAccessToken(token, {
|
|
47
|
+
domain: process.env.SSO_ID_DOMAIN || 'acme.sso.id',
|
|
48
|
+
audience: process.env.SSO_ID_AUDIENCE || undefined,
|
|
49
|
+
});
|
|
50
|
+
return next();
|
|
51
|
+
} catch (err) {
|
|
52
|
+
return res.status(401).json({ error: err.message });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
app.get('/api/me', requiresAuth(), (req, res) => {
|
|
57
|
+
res.json({ user: req.oidc.user });
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
// 2. Organizations, OUs, Users, Groups (Management API)
|
|
61
|
+
app.get('/api/organizations', requireBearerOrSession, async (_req, res) => {
|
|
62
|
+
res.json(await mgmt.organizations.list());
|
|
63
|
+
});
|
|
64
|
+
app.post('/api/organizations', requireBearerOrSession, async (req, res) => {
|
|
65
|
+
res.status(201).json(await mgmt.organizations.create(req.body));
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
app.get('/api/organization-units', requireBearerOrSession, async (req, res) => {
|
|
69
|
+
const orgId = req.query.organizationId;
|
|
70
|
+
res.json(orgId ? await mgmt.organizationUnits.listByOrganization(String(orgId)) : await mgmt.organizationUnits.list());
|
|
71
|
+
});
|
|
72
|
+
app.post('/api/organization-units', requireBearerOrSession, async (req, res) => {
|
|
73
|
+
res.status(201).json(await mgmt.organizationUnits.create(req.body));
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
app.get('/api/users', requireBearerOrSession, async (_req, res) => {
|
|
77
|
+
res.json(await mgmt.users.list({ page: 1, pageSize: 50 }));
|
|
78
|
+
});
|
|
79
|
+
app.post('/api/users', requireBearerOrSession, async (req, res) => {
|
|
80
|
+
res.status(201).json(await mgmt.users.create(req.body));
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
app.get('/api/groups', requireBearerOrSession, async (_req, res) => {
|
|
84
|
+
res.json(await mgmt.groups.list());
|
|
85
|
+
});
|
|
86
|
+
app.post('/api/groups', requireBearerOrSession, async (req, res) => {
|
|
87
|
+
res.status(201).json(await mgmt.groups.create(req.body));
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
// 3. Real-Time SCIM 2.0 Provisioning Endpoints
|
|
91
|
+
const scimUsers = new Map();
|
|
92
|
+
const scimGroups = new Map();
|
|
93
|
+
const scimEvents = [];
|
|
94
|
+
|
|
95
|
+
function requireScimAuth(req, res, next) {
|
|
96
|
+
if (!verifyScimBearerToken(req.headers.authorization, process.env.SSO_ID_SCIM_BEARER_TOKEN || '')) {
|
|
97
|
+
return res.status(401).json(formatScimError('Unauthorized SCIM request', 401));
|
|
98
|
+
}
|
|
99
|
+
return next();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
app.get('/scim/v2/Users', requireScimAuth, (_req, res) => {
|
|
103
|
+
res.json(formatScimListResponse(Array.from(scimUsers.values())));
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
app.post('/scim/v2/Users', requireScimAuth, (req, res) => {
|
|
107
|
+
const id = req.body.id || randomUUID();
|
|
108
|
+
const user = {
|
|
109
|
+
schemas: [SCIM_CORE_USER_SCHEMA],
|
|
110
|
+
active: true,
|
|
111
|
+
...req.body,
|
|
112
|
+
id,
|
|
113
|
+
meta: { resourceType: 'User', lastModified: new Date().toISOString() },
|
|
114
|
+
};
|
|
115
|
+
scimUsers.set(id, user);
|
|
116
|
+
scimEvents.unshift({ type: 'User', op: 'CREATE', id, userName: user.userName, at: new Date().toISOString() });
|
|
117
|
+
res.status(201).json(user);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
app.put('/scim/v2/Users/:id', requireScimAuth, (req, res) => {
|
|
121
|
+
const user = { ...req.body, id: req.params.id, meta: { resourceType: 'User', lastModified: new Date().toISOString() } };
|
|
122
|
+
scimUsers.set(req.params.id, user);
|
|
123
|
+
scimEvents.unshift({ type: 'User', op: 'UPDATE', id: req.params.id, at: new Date().toISOString() });
|
|
124
|
+
res.json(user);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
app.patch('/scim/v2/Users/:id', requireScimAuth, (req, res) => {
|
|
128
|
+
const existing = scimUsers.get(req.params.id);
|
|
129
|
+
if (!existing) return res.status(404).json(formatScimError('User not found', 404));
|
|
130
|
+
for (const op of req.body.Operations || []) {
|
|
131
|
+
if (op.path === 'active') existing.active = Boolean(op.value);
|
|
132
|
+
if (!op.path && typeof op.value === 'object') Object.assign(existing, op.value);
|
|
133
|
+
}
|
|
134
|
+
scimEvents.unshift({ type: 'User', op: 'PATCH', id: req.params.id, at: new Date().toISOString() });
|
|
135
|
+
res.json(existing);
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
app.delete('/scim/v2/Users/:id', requireScimAuth, (req, res) => {
|
|
139
|
+
scimUsers.delete(req.params.id);
|
|
140
|
+
scimEvents.unshift({ type: 'User', op: 'DELETE', id: req.params.id, at: new Date().toISOString() });
|
|
141
|
+
res.status(204).end();
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
app.get('/scim/v2/Groups', requireScimAuth, (_req, res) => {
|
|
145
|
+
res.json(formatScimListResponse(Array.from(scimGroups.values())));
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
app.post('/scim/v2/Groups', requireScimAuth, (req, res) => {
|
|
149
|
+
const id = req.body.id || randomUUID();
|
|
150
|
+
const group = {
|
|
151
|
+
schemas: [SCIM_CORE_GROUP_SCHEMA],
|
|
152
|
+
members: [],
|
|
153
|
+
...req.body,
|
|
154
|
+
id,
|
|
155
|
+
meta: { resourceType: 'Group', lastModified: new Date().toISOString() },
|
|
156
|
+
};
|
|
157
|
+
scimGroups.set(id, group);
|
|
158
|
+
scimEvents.unshift({ type: 'Group', op: 'CREATE', id, displayName: group.displayName, at: new Date().toISOString() });
|
|
159
|
+
res.status(201).json(group);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
app.get('/api/scim/events', requireBearerOrSession, (_req, res) => {
|
|
163
|
+
res.json({ users: Array.from(scimUsers.values()), groups: Array.from(scimGroups.values()), events: scimEvents });
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
app.post('/api/scim/push-user', requireBearerOrSession, async (req, res) => {
|
|
167
|
+
const scim = mgmt.scim.forConnection(process.env.SSO_ID_SCIM_CONNECTION_ID || undefined);
|
|
168
|
+
const created = await scim.createUser({
|
|
169
|
+
schemas: [SCIM_CORE_USER_SCHEMA],
|
|
170
|
+
userName: req.body.userName || req.body.email,
|
|
171
|
+
displayName: req.body.displayName,
|
|
172
|
+
emails: req.body.email ? [{ value: req.body.email, primary: true }] : [],
|
|
173
|
+
active: true,
|
|
174
|
+
});
|
|
175
|
+
res.status(201).json(created);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
const port = Number(process.env.PORT || 4000);
|
|
179
|
+
app.listen(port, () => {
|
|
180
|
+
console.log(`SSO.ID Express + SCIM + Management API listening on http://localhost:${port}`);
|
|
181
|
+
});
|
|
182
|
+
|