@sso-id/cli 0.2.0 → 0.2.2
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 +54 -2
- package/package.json +1 -1
- package/templates/angular-spa/angular.json +30 -0
- package/templates/angular-spa/dev.mjs +73 -0
- package/templates/angular-spa/package.json +16 -3
- package/templates/angular-spa/src/index.html +12 -0
- package/templates/angular-spa/src/main.ts +5 -0
- package/templates/angular-spa/tsconfig.json +11 -0
- package/templates/dotnet-api/Program.cs +59 -45
- package/templates/dotnet-api/SsoIdStarter.csproj +1 -3
- package/templates/go-gin/go.mod +0 -3
- package/templates/go-gin/main.go +68 -4
- package/templates/mobile-react-native/App.tsx +47 -21
- package/templates/php-laravel/composer.json +1 -3
- package/templates/php-laravel/public/index.php +42 -5
- package/templates/python-fastapi/main.py +15 -3
- package/templates/python-fastapi/requirements.txt +1 -2
- package/templates/react-spa/dev.mjs +94 -0
- package/templates/react-spa/index.html +12 -0
- package/templates/react-spa/package.json +5 -2
- package/templates/react-spa/tsconfig.json +13 -0
- package/templates/react-spa/vite.config.ts +13 -0
- package/templates/vue-spa/dev.mjs +94 -0
- package/templates/vue-spa/index.html +12 -0
- package/templates/vue-spa/package.json +5 -2
- package/templates/vue-spa/vite.config.ts +13 -0
package/bin/sso-id.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
2
3
|
import { cpSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
4
|
import { dirname, join, resolve } from 'node:path';
|
|
4
5
|
import { fileURLToPath } from 'node:url';
|
|
@@ -62,6 +63,7 @@ export function parseFlags(argv) {
|
|
|
62
63
|
|
|
63
64
|
export function applyEnvOverrides(templateEnv, overrides) {
|
|
64
65
|
let content = templateEnv;
|
|
66
|
+
const sessionSecret = overrides.sessionSecret || randomBytes(32).toString('hex');
|
|
65
67
|
const replacements = {
|
|
66
68
|
SSO_ID_DOMAIN: overrides.domain,
|
|
67
69
|
NEXT_PUBLIC_SSO_ID_DOMAIN: overrides.domain,
|
|
@@ -70,9 +72,16 @@ export function applyEnvOverrides(templateEnv, overrides) {
|
|
|
70
72
|
NEXT_PUBLIC_SSO_ID_CLIENT_ID: overrides.clientId,
|
|
71
73
|
VITE_SSO_ID_CLIENT_ID: overrides.clientId,
|
|
72
74
|
SSO_ID_CLIENT_SECRET: overrides.clientSecret,
|
|
73
|
-
|
|
74
|
-
|
|
75
|
+
SSO_ID_REDIRECT_URI: overrides.redirectUri,
|
|
76
|
+
NEXT_PUBLIC_SSO_ID_REDIRECT_URI: overrides.redirectUri,
|
|
77
|
+
VITE_SSO_ID_REDIRECT_URI: overrides.redirectUri,
|
|
78
|
+
SSO_ID_M2M_CLIENT_ID: overrides.m2mClientId || overrides.clientId,
|
|
79
|
+
SSO_ID_M2M_CLIENT_SECRET: overrides.m2mClientSecret || overrides.clientSecret,
|
|
80
|
+
SSO_ID_API_BASE_URL: overrides.apiBaseUrl,
|
|
81
|
+
SSO_ID_AUDIENCE: overrides.audience,
|
|
82
|
+
SSO_ID_SESSION_SECRET: sessionSecret,
|
|
75
83
|
SSO_ID_SCIM_BEARER_TOKEN: overrides.scimToken,
|
|
84
|
+
SSO_ID_SCIM_CONNECTION_ID: overrides.scimConnectionId,
|
|
76
85
|
};
|
|
77
86
|
for (const [key, val] of Object.entries(replacements)) {
|
|
78
87
|
if (!val) continue;
|
|
@@ -86,6 +95,41 @@ export function applyEnvOverrides(templateEnv, overrides) {
|
|
|
86
95
|
return `${content.trimEnd()}\n`;
|
|
87
96
|
}
|
|
88
97
|
|
|
98
|
+
function patchStructuredConfigs(destDir, overrides) {
|
|
99
|
+
const angularEnvPath = join(destDir, 'src', 'environments', 'environment.ts');
|
|
100
|
+
if (existsSync(angularEnvPath)) {
|
|
101
|
+
let ngEnv = readFileSync(angularEnvPath, 'utf8');
|
|
102
|
+
if (overrides.domain) ngEnv = ngEnv.replace(/ssoIdDomain:\s*'[^']*'/, `ssoIdDomain: '${overrides.domain}'`);
|
|
103
|
+
if (overrides.clientId) ngEnv = ngEnv.replace(/ssoIdClientId:\s*'[^']*'/, `ssoIdClientId: '${overrides.clientId}'`);
|
|
104
|
+
if (overrides.redirectUri) ngEnv = ngEnv.replace(/ssoIdRedirectUri:\s*'[^']*'/, `ssoIdRedirectUri: '${overrides.redirectUri}'`);
|
|
105
|
+
writeFileSync(angularEnvPath, ngEnv, 'utf8');
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const rnAppPath = join(destDir, 'App.tsx');
|
|
109
|
+
if (existsSync(rnAppPath)) {
|
|
110
|
+
let rnApp = readFileSync(rnAppPath, 'utf8');
|
|
111
|
+
if (overrides.domain) rnApp = rnApp.replace(/domain:\s*'[^']*'/, `domain: '${overrides.domain}'`);
|
|
112
|
+
if (overrides.clientId) rnApp = rnApp.replace(/clientId:\s*'[^']*'/, `clientId: '${overrides.clientId}'`);
|
|
113
|
+
if (overrides.redirectUri) rnApp = rnApp.replace(/redirectUri:\s*'[^']*'/, `redirectUri: '${overrides.redirectUri}'`);
|
|
114
|
+
writeFileSync(rnAppPath, rnApp, 'utf8');
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const appsettingsPath = join(destDir, 'appsettings.json');
|
|
118
|
+
if (existsSync(appsettingsPath)) {
|
|
119
|
+
const cfg = JSON.parse(readFileSync(appsettingsPath, 'utf8'));
|
|
120
|
+
cfg.SsoId = cfg.SsoId || {};
|
|
121
|
+
cfg.Scim = cfg.Scim || {};
|
|
122
|
+
if (overrides.domain) cfg.SsoId.Domain = overrides.domain;
|
|
123
|
+
if (overrides.m2mClientId || overrides.clientId) cfg.SsoId.ClientId = overrides.m2mClientId || overrides.clientId;
|
|
124
|
+
if (overrides.m2mClientSecret || overrides.clientSecret) cfg.SsoId.ClientSecret = overrides.m2mClientSecret || overrides.clientSecret;
|
|
125
|
+
if (overrides.apiBaseUrl) cfg.SsoId.ApiBaseUrl = overrides.apiBaseUrl;
|
|
126
|
+
if (overrides.audience) cfg.SsoId.Audience = overrides.audience;
|
|
127
|
+
if (overrides.scimToken) cfg.Scim.BearerToken = overrides.scimToken;
|
|
128
|
+
if (overrides.scimConnectionId) cfg.Scim.ConnectionId = overrides.scimConnectionId;
|
|
129
|
+
writeFileSync(appsettingsPath, `${JSON.stringify(cfg, null, 2)}\n`, 'utf8');
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
89
133
|
export function scaffoldTemplate(templateName, targetDir, overrides = {}) {
|
|
90
134
|
if (!AVAILABLE_TEMPLATES.includes(templateName)) {
|
|
91
135
|
throw new Error(`Unknown template "${templateName}". Available: ${AVAILABLE_TEMPLATES.join(', ')}`);
|
|
@@ -104,6 +148,7 @@ export function scaffoldTemplate(templateName, targetDir, overrides = {}) {
|
|
|
104
148
|
? readFileSync(envExamplePath, 'utf8')
|
|
105
149
|
: generateEnvTemplate({ domain: 'acme.sso.id', clientId: 'YOUR_CLIENT_ID', ...overrides });
|
|
106
150
|
writeFileSync(join(destDir, '.env'), applyEnvOverrides(baseEnv, overrides), 'utf8');
|
|
151
|
+
patchStructuredConfigs(destDir, overrides);
|
|
107
152
|
} else {
|
|
108
153
|
writeFileSync(
|
|
109
154
|
join(destDir, '.env'),
|
|
@@ -141,7 +186,14 @@ async function main() {
|
|
|
141
186
|
domain: flags.domain,
|
|
142
187
|
clientId: flags['client-id'],
|
|
143
188
|
clientSecret: flags['client-secret'],
|
|
189
|
+
m2mClientId: flags['m2m-client-id'],
|
|
190
|
+
m2mClientSecret: flags['m2m-client-secret'],
|
|
191
|
+
redirectUri: flags['redirect-uri'],
|
|
192
|
+
apiBaseUrl: flags['api-base-url'],
|
|
193
|
+
sessionSecret: flags['session-secret'],
|
|
194
|
+
audience: flags.audience,
|
|
144
195
|
scimToken: flags['scim-token'],
|
|
196
|
+
scimConnectionId: flags['scim-connection-id'],
|
|
145
197
|
});
|
|
146
198
|
console.log(`Created SSO.ID "${arg1}" starter at: ${dest}`);
|
|
147
199
|
return;
|
package/package.json
CHANGED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
|
|
3
|
+
"version": 1,
|
|
4
|
+
"projects": {
|
|
5
|
+
"sso-id-angular-template": {
|
|
6
|
+
"projectType": "application",
|
|
7
|
+
"root": "",
|
|
8
|
+
"sourceRoot": "src",
|
|
9
|
+
"architect": {
|
|
10
|
+
"build": {
|
|
11
|
+
"builder": "@angular-devkit/build-angular:application",
|
|
12
|
+
"options": {
|
|
13
|
+
"outputPath": "dist",
|
|
14
|
+
"index": "src/index.html",
|
|
15
|
+
"browser": "src/main.ts",
|
|
16
|
+
"polyfills": ["zone.js"],
|
|
17
|
+
"tsConfig": "tsconfig.json"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"serve": {
|
|
21
|
+
"builder": "@angular-devkit/build-angular:dev-server",
|
|
22
|
+
"options": {
|
|
23
|
+
"buildTarget": "sso-id-angular-template:build",
|
|
24
|
+
"port": 4200
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import 'dotenv/config';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import express from 'express';
|
|
5
|
+
import cors from 'cors';
|
|
6
|
+
import {
|
|
7
|
+
ManagementClient,
|
|
8
|
+
verifyScimBearerToken,
|
|
9
|
+
formatScimListResponse,
|
|
10
|
+
formatScimError,
|
|
11
|
+
SCIM_CORE_USER_SCHEMA,
|
|
12
|
+
SCIM_CORE_GROUP_SCHEMA,
|
|
13
|
+
} from '@sso-id/node';
|
|
14
|
+
|
|
15
|
+
const app = express();
|
|
16
|
+
app.use(cors());
|
|
17
|
+
app.use(express.json({ type: ['application/json', 'application/scim+json'] }));
|
|
18
|
+
|
|
19
|
+
const mgmt = new ManagementClient({
|
|
20
|
+
domain: process.env.SSO_ID_DOMAIN || 'acme.sso.id',
|
|
21
|
+
clientId: process.env.SSO_ID_M2M_CLIENT_ID || process.env.SSO_ID_CLIENT_ID || '',
|
|
22
|
+
clientSecret: process.env.SSO_ID_M2M_CLIENT_SECRET || process.env.SSO_ID_CLIENT_SECRET || '',
|
|
23
|
+
apiBaseUrl: process.env.SSO_ID_API_BASE_URL || 'https://api.sso.id',
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
app.get('/api/organizations', async (_req, res) => { try { res.json(await mgmt.organizations.list()); } catch (e) { res.status(500).json({ error: e.message }); } });
|
|
27
|
+
app.post('/api/organizations', async (req, res) => { try { res.status(201).json(await mgmt.organizations.create(req.body)); } catch (e) { res.status(500).json({ error: e.message }); } });
|
|
28
|
+
app.get('/api/organization-units', async (req, res) => { try { res.json(req.query.organizationId ? await mgmt.organizationUnits.listByOrganization(String(req.query.organizationId)) : await mgmt.organizationUnits.list()); } catch (e) { res.status(500).json({ error: e.message }); } });
|
|
29
|
+
app.post('/api/organization-units', async (req, res) => { try { res.status(201).json(await mgmt.organizationUnits.create(req.body)); } catch (e) { res.status(500).json({ error: e.message }); } });
|
|
30
|
+
app.get('/api/users', async (_req, res) => { try { res.json(await mgmt.users.list({ page: 1, pageSize: 50 })); } catch (e) { res.status(500).json({ error: e.message }); } });
|
|
31
|
+
app.post('/api/users', async (req, res) => { try { res.status(201).json(await mgmt.users.create(req.body)); } catch (e) { res.status(500).json({ error: e.message }); } });
|
|
32
|
+
app.get('/api/groups', async (_req, res) => { try { res.json(await mgmt.groups.list()); } catch (e) { res.status(500).json({ error: e.message }); } });
|
|
33
|
+
app.post('/api/groups', async (req, res) => { try { res.status(201).json(await mgmt.groups.create(req.body)); } catch (e) { res.status(500).json({ error: e.message }); } });
|
|
34
|
+
|
|
35
|
+
const scimUsers = new Map();
|
|
36
|
+
const scimGroups = new Map();
|
|
37
|
+
const scimEvents = [];
|
|
38
|
+
|
|
39
|
+
function requireScim(req, res, next) {
|
|
40
|
+
if (!verifyScimBearerToken(req.headers.authorization, process.env.SSO_ID_SCIM_BEARER_TOKEN || '')) {
|
|
41
|
+
return res.status(401).json(formatScimError('Unauthorized SCIM request', 401));
|
|
42
|
+
}
|
|
43
|
+
return next();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
app.get('/scim/v2/Users', requireScim, (_req, res) => res.json(formatScimListResponse(Array.from(scimUsers.values()))));
|
|
47
|
+
app.post('/scim/v2/Users', requireScim, (req, res) => {
|
|
48
|
+
const id = req.body.id || randomUUID();
|
|
49
|
+
const u = { schemas: [SCIM_CORE_USER_SCHEMA], active: true, ...req.body, id };
|
|
50
|
+
scimUsers.set(id, u);
|
|
51
|
+
scimEvents.unshift({ type: 'User', op: 'CREATE', id, userName: u.userName, at: new Date().toISOString() });
|
|
52
|
+
res.status(201).json(u);
|
|
53
|
+
});
|
|
54
|
+
app.get('/scim/v2/Groups', requireScim, (_req, res) => res.json(formatScimListResponse(Array.from(scimGroups.values()))));
|
|
55
|
+
app.post('/scim/v2/Groups', requireScim, (req, res) => {
|
|
56
|
+
const id = req.body.id || randomUUID();
|
|
57
|
+
const g = { schemas: [SCIM_CORE_GROUP_SCHEMA], members: [], ...req.body, id };
|
|
58
|
+
scimGroups.set(id, g);
|
|
59
|
+
scimEvents.unshift({ type: 'Group', op: 'CREATE', id, displayName: g.displayName, at: new Date().toISOString() });
|
|
60
|
+
res.status(201).json(g);
|
|
61
|
+
});
|
|
62
|
+
app.get('/api/scim/events', (_req, res) => res.json({ users: Array.from(scimUsers.values()), groups: Array.from(scimGroups.values()), events: scimEvents }));
|
|
63
|
+
app.post('/api/scim/push-user', async (req, res) => {
|
|
64
|
+
try {
|
|
65
|
+
const scim = mgmt.scim.forConnection(process.env.SSO_ID_SCIM_CONNECTION_ID || undefined);
|
|
66
|
+
res.status(201).json(await scim.createUser({ schemas: [SCIM_CORE_USER_SCHEMA], userName: req.body.userName, displayName: req.body.displayName, active: true }));
|
|
67
|
+
} catch (e) { res.status(500).json({ error: e.message }); }
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
app.listen(5000, () => {
|
|
71
|
+
console.log('SSO.ID Management & SCIM 2.0 API running on http://localhost:5000');
|
|
72
|
+
spawn('npx', ['ng', 'serve'], { stdio: 'inherit', shell: true });
|
|
73
|
+
});
|
|
@@ -2,18 +2,31 @@
|
|
|
2
2
|
"name": "sso-id-angular-template",
|
|
3
3
|
"version": "0.1.0",
|
|
4
4
|
"private": true,
|
|
5
|
+
"type": "module",
|
|
5
6
|
"scripts": {
|
|
6
|
-
"start": "
|
|
7
|
+
"start": "node dev.mjs",
|
|
7
8
|
"build": "ng build"
|
|
8
9
|
},
|
|
9
10
|
"dependencies": {
|
|
10
11
|
"@angular/common": "^18.2.0",
|
|
12
|
+
"@angular/compiler": "^18.2.0",
|
|
11
13
|
"@angular/core": "^18.2.0",
|
|
12
14
|
"@angular/forms": "^18.2.0",
|
|
13
15
|
"@angular/platform-browser": "^18.2.0",
|
|
14
16
|
"@angular/router": "^18.2.0",
|
|
15
17
|
"@sso-id/angular": "^0.1.0",
|
|
16
|
-
"
|
|
18
|
+
"@sso-id/node": "^0.2.0",
|
|
19
|
+
"cors": "^2.8.5",
|
|
20
|
+
"dotenv": "^16.4.5",
|
|
21
|
+
"express": "^4.21.0",
|
|
22
|
+
"rxjs": "^7.8.1",
|
|
23
|
+
"tslib": "^2.6.0",
|
|
24
|
+
"zone.js": "~0.14.10"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@angular-devkit/build-angular": "^18.2.0",
|
|
28
|
+
"@angular/cli": "^18.2.0",
|
|
29
|
+
"@angular/compiler-cli": "^18.2.0",
|
|
30
|
+
"typescript": "~5.5.2"
|
|
17
31
|
}
|
|
18
32
|
}
|
|
19
|
-
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8" />
|
|
5
|
+
<title>SSO.ID Angular Starter — Auth, Orgs, OUs, Users, Groups & SCIM 2.0</title>
|
|
6
|
+
<base href="/" />
|
|
7
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
8
|
+
</head>
|
|
9
|
+
<body style="margin:0;background:#f8fafc;color:#0f172a">
|
|
10
|
+
<app-root></app-root>
|
|
11
|
+
</body>
|
|
12
|
+
</html>
|
|
@@ -1,31 +1,39 @@
|
|
|
1
1
|
using System.Collections.Concurrent;
|
|
2
|
+
using System.Net.Http.Headers;
|
|
2
3
|
using System.Security.Cryptography;
|
|
3
4
|
using System.Text;
|
|
4
5
|
using System.Text.Json;
|
|
6
|
+
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
5
7
|
using Microsoft.AspNetCore.Authorization;
|
|
6
|
-
using
|
|
7
|
-
using SsoId.ManagementApi;
|
|
8
|
+
using Microsoft.IdentityModel.Tokens;
|
|
8
9
|
|
|
9
10
|
var builder = WebApplication.CreateBuilder(args);
|
|
10
11
|
|
|
11
|
-
var domain = builder.Configuration["SsoId:Domain"] ?? "acme.sso.id";
|
|
12
|
-
var
|
|
12
|
+
var domain = (builder.Configuration["SsoId:Domain"] ?? "acme.sso.id").Trim().TrimEnd('/');
|
|
13
|
+
var authority = domain.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? domain : $"https://{domain}";
|
|
14
|
+
var audience = builder.Configuration["SsoId:Audience"];
|
|
15
|
+
var clientId = builder.Configuration["SsoId:ClientId"] ?? "";
|
|
16
|
+
var clientSecret = builder.Configuration["SsoId:ClientSecret"] ?? "";
|
|
17
|
+
var apiBaseUrl = (builder.Configuration["SsoId:ApiBaseUrl"] ?? "https://api.sso.id").TrimEnd('/');
|
|
13
18
|
var scimToken = builder.Configuration["Scim:BearerToken"] ?? "";
|
|
14
19
|
|
|
15
|
-
builder.Services
|
|
16
|
-
|
|
17
|
-
opts
|
|
18
|
-
|
|
19
|
-
}
|
|
20
|
+
builder.Services
|
|
21
|
+
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
|
22
|
+
.AddJwtBearer(opts =>
|
|
23
|
+
{
|
|
24
|
+
opts.MetadataAddress = $"{authority}/auth/.well-known/openid-configuration";
|
|
25
|
+
opts.TokenValidationParameters = new TokenValidationParameters
|
|
26
|
+
{
|
|
27
|
+
ValidateIssuer = true,
|
|
28
|
+
ValidIssuers = new[] { authority, $"{authority}/auth" },
|
|
29
|
+
ValidateAudience = !string.IsNullOrWhiteSpace(audience),
|
|
30
|
+
ValidAudience = audience,
|
|
31
|
+
ValidateLifetime = true,
|
|
32
|
+
};
|
|
33
|
+
});
|
|
20
34
|
|
|
21
|
-
builder.Services.
|
|
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>();
|
|
35
|
+
builder.Services.AddAuthorization();
|
|
36
|
+
builder.Services.AddHttpClient("ssoid");
|
|
29
37
|
builder.Services.AddCors(o => o.AddDefaultPolicy(p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
|
|
30
38
|
|
|
31
39
|
var app = builder.Build();
|
|
@@ -33,6 +41,28 @@ app.UseCors();
|
|
|
33
41
|
app.UseAuthentication();
|
|
34
42
|
app.UseAuthorization();
|
|
35
43
|
|
|
44
|
+
async Task<IResult> ProxyManagementAsync(IHttpClientFactory httpFactory, HttpMethod method, string path, JsonElement? payload = null)
|
|
45
|
+
{
|
|
46
|
+
var client = httpFactory.CreateClient("ssoid");
|
|
47
|
+
using var tokenRes = await client.PostAsync($"{authority}/auth/oauth/token", new FormUrlEncodedContent(new Dictionary<string, string>
|
|
48
|
+
{
|
|
49
|
+
["grant_type"] = "client_credentials",
|
|
50
|
+
["client_id"] = clientId,
|
|
51
|
+
["client_secret"] = clientSecret,
|
|
52
|
+
}));
|
|
53
|
+
tokenRes.EnsureSuccessStatusCode();
|
|
54
|
+
using var tokenDoc = await tokenRes.Content.ReadFromJsonAsync<JsonDocument>();
|
|
55
|
+
var accessToken = tokenDoc!.RootElement.GetProperty("access_token").GetString();
|
|
56
|
+
|
|
57
|
+
using var req = new HttpRequestMessage(method, $"{apiBaseUrl}{path}");
|
|
58
|
+
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
|
|
59
|
+
if (payload.HasValue) req.Content = JsonContent.Create(payload.Value);
|
|
60
|
+
|
|
61
|
+
using var res = await client.SendAsync(req);
|
|
62
|
+
var json = await res.Content.ReadFromJsonAsync<JsonElement>();
|
|
63
|
+
return Results.Json(json, statusCode: (int)res.StatusCode);
|
|
64
|
+
}
|
|
65
|
+
|
|
36
66
|
var scimUsers = new ConcurrentDictionary<string, JsonElement>();
|
|
37
67
|
var scimGroups = new ConcurrentDictionary<string, JsonElement>();
|
|
38
68
|
var scimEvents = new ConcurrentQueue<object>();
|
|
@@ -47,32 +77,24 @@ bool ValidScimToken(HttpRequest req)
|
|
|
47
77
|
return a.Length == b.Length && CryptographicOperations.FixedTimeEquals(a, b);
|
|
48
78
|
}
|
|
49
79
|
|
|
50
|
-
|
|
51
|
-
app.
|
|
52
|
-
app.MapPost("/api/organizations", [Authorize] (JsonElement body, ISsoManagementClient mgmt, CancellationToken ct) => mgmt.CreateOrganizationAsync(body, ct));
|
|
80
|
+
app.MapGet("/api/organizations", (IHttpClientFactory f) => ProxyManagementAsync(f, HttpMethod.Get, "/api/organizations"));
|
|
81
|
+
app.MapPost("/api/organizations", (JsonElement body, IHttpClientFactory f) => ProxyManagementAsync(f, HttpMethod.Post, "/api/organizations", body));
|
|
53
82
|
|
|
54
|
-
app.MapGet("/api/organization-units",
|
|
55
|
-
|
|
83
|
+
app.MapGet("/api/organization-units", (string? organizationId, IHttpClientFactory f) =>
|
|
84
|
+
ProxyManagementAsync(f, HttpMethod.Get, string.IsNullOrWhiteSpace(organizationId) ? "/api/organization-units" : $"/api/organization-units/organizationunit/organization/{Uri.EscapeDataString(organizationId)}"));
|
|
85
|
+
app.MapPost("/api/organization-units", (JsonElement body, IHttpClientFactory f) => ProxyManagementAsync(f, HttpMethod.Post, "/api/organization-units", body));
|
|
56
86
|
|
|
57
|
-
app.MapGet("/api/users",
|
|
58
|
-
app.MapPost("/api/users",
|
|
87
|
+
app.MapGet("/api/users", (IHttpClientFactory f) => ProxyManagementAsync(f, HttpMethod.Get, "/api/users?page=1&pageSize=50"));
|
|
88
|
+
app.MapPost("/api/users", (JsonElement body, IHttpClientFactory f) => ProxyManagementAsync(f, HttpMethod.Post, "/api/users", body));
|
|
59
89
|
|
|
60
|
-
app.MapGet("/api/groups",
|
|
61
|
-
app.MapPost("/api/groups",
|
|
90
|
+
app.MapGet("/api/groups", (IHttpClientFactory f) => ProxyManagementAsync(f, HttpMethod.Get, "/api/groups"));
|
|
91
|
+
app.MapPost("/api/groups", (JsonElement body, IHttpClientFactory f) => ProxyManagementAsync(f, HttpMethod.Post, "/api/groups", body));
|
|
62
92
|
|
|
63
|
-
// Real-Time SCIM 2.0 Receiver
|
|
64
93
|
app.MapGet("/scim/v2/Users", (HttpRequest req) =>
|
|
65
94
|
{
|
|
66
95
|
if (!ValidScimToken(req)) return Results.Unauthorized();
|
|
67
96
|
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
|
-
});
|
|
97
|
+
return Results.Ok(new { schemas = new[] { "urn:ietf:params:scim:api:messages:2.0:ListResponse" }, totalResults = list.Count, startIndex = 1, itemsPerPage = list.Count, Resources = list });
|
|
76
98
|
});
|
|
77
99
|
|
|
78
100
|
app.MapPost("/scim/v2/Users", (HttpRequest req, JsonElement body) =>
|
|
@@ -96,14 +118,7 @@ app.MapGet("/scim/v2/Groups", (HttpRequest req) =>
|
|
|
96
118
|
{
|
|
97
119
|
if (!ValidScimToken(req)) return Results.Unauthorized();
|
|
98
120
|
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
|
-
});
|
|
121
|
+
return Results.Ok(new { schemas = new[] { "urn:ietf:params:scim:api:messages:2.0:ListResponse" }, totalResults = list.Count, startIndex = 1, itemsPerPage = list.Count, Resources = list });
|
|
107
122
|
});
|
|
108
123
|
|
|
109
124
|
app.MapPost("/scim/v2/Groups", (HttpRequest req, JsonElement body) =>
|
|
@@ -115,7 +130,6 @@ app.MapPost("/scim/v2/Groups", (HttpRequest req, JsonElement body) =>
|
|
|
115
130
|
return Results.Created($"/scim/v2/Groups/{id}", body);
|
|
116
131
|
});
|
|
117
132
|
|
|
118
|
-
app.MapGet("/api/scim/events",
|
|
133
|
+
app.MapGet("/api/scim/events", () => Results.Ok(new { users = scimUsers.Values, groups = scimGroups.Values, events = scimEvents }));
|
|
119
134
|
|
|
120
135
|
app.Run();
|
|
121
|
-
|
|
@@ -5,8 +5,6 @@
|
|
|
5
5
|
<ImplicitUsings>enable</ImplicitUsings>
|
|
6
6
|
</PropertyGroup>
|
|
7
7
|
<ItemGroup>
|
|
8
|
-
<PackageReference Include="
|
|
9
|
-
<PackageReference Include="SsoId.ManagementApi" Version="0.1.0" />
|
|
8
|
+
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.10" />
|
|
10
9
|
</ItemGroup>
|
|
11
10
|
</Project>
|
|
12
|
-
|
package/templates/go-gin/go.mod
CHANGED
package/templates/go-gin/main.go
CHANGED
|
@@ -1,17 +1,73 @@
|
|
|
1
1
|
package main
|
|
2
2
|
|
|
3
3
|
import (
|
|
4
|
+
"bytes"
|
|
4
5
|
"crypto/subtle"
|
|
5
6
|
"encoding/json"
|
|
7
|
+
"io"
|
|
6
8
|
"log"
|
|
7
9
|
"net/http"
|
|
10
|
+
"net/url"
|
|
8
11
|
"os"
|
|
9
12
|
"strings"
|
|
10
13
|
"sync"
|
|
11
14
|
)
|
|
12
15
|
|
|
16
|
+
func getM2MToken(domain, clientID, clientSecret string) (string, error) {
|
|
17
|
+
authBase := strings.TrimRight(domain, "/")
|
|
18
|
+
if !strings.HasPrefix(authBase, "http") {
|
|
19
|
+
authBase = "https://" + authBase
|
|
20
|
+
}
|
|
21
|
+
res, err := http.PostForm(authBase+"/auth/oauth/token", url.Values{
|
|
22
|
+
"grant_type": {"client_credentials"},
|
|
23
|
+
"client_id": {clientID},
|
|
24
|
+
"client_secret": {clientSecret},
|
|
25
|
+
})
|
|
26
|
+
if err != nil {
|
|
27
|
+
return "", err
|
|
28
|
+
}
|
|
29
|
+
defer res.Body.Close()
|
|
30
|
+
var doc map[string]any
|
|
31
|
+
_ = json.NewDecoder(res.Body).Decode(&doc)
|
|
32
|
+
tok, _ := doc["access_token"].(string)
|
|
33
|
+
return tok, nil
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
func proxyMgmt(w http.ResponseWriter, r *http.Request, domain, clientID, clientSecret, apiBase, targetPath string) {
|
|
37
|
+
tok, err := getM2MToken(domain, clientID, clientSecret)
|
|
38
|
+
if err != nil {
|
|
39
|
+
http.Error(w, err.Error(), http.StatusBadGateway)
|
|
40
|
+
return
|
|
41
|
+
}
|
|
42
|
+
var bodyReader io.Reader
|
|
43
|
+
if r.Body != nil {
|
|
44
|
+
b, _ := io.ReadAll(r.Body)
|
|
45
|
+
bodyReader = bytes.NewReader(b)
|
|
46
|
+
}
|
|
47
|
+
req, _ := http.NewRequest(r.Method, strings.TrimRight(apiBase, "/")+targetPath, bodyReader)
|
|
48
|
+
req.Header.Set("Authorization", "Bearer "+tok)
|
|
49
|
+
req.Header.Set("Content-Type", "application/json")
|
|
50
|
+
resp, err := http.DefaultClient.Do(req)
|
|
51
|
+
if err != nil {
|
|
52
|
+
http.Error(w, err.Error(), http.StatusBadGateway)
|
|
53
|
+
return
|
|
54
|
+
}
|
|
55
|
+
defer resp.Body.Close()
|
|
56
|
+
w.Header().Set("Content-Type", "application/json")
|
|
57
|
+
w.WriteHeader(resp.StatusCode)
|
|
58
|
+
_, _ = io.Copy(w, resp.Body)
|
|
59
|
+
}
|
|
60
|
+
|
|
13
61
|
func main() {
|
|
62
|
+
domain := os.Getenv("SSO_ID_DOMAIN")
|
|
63
|
+
clientID := os.Getenv("SSO_ID_CLIENT_ID")
|
|
64
|
+
clientSecret := os.Getenv("SSO_ID_CLIENT_SECRET")
|
|
65
|
+
apiBase := os.Getenv("SSO_ID_API_BASE_URL")
|
|
66
|
+
if apiBase == "" {
|
|
67
|
+
apiBase = "https://api.sso.id"
|
|
68
|
+
}
|
|
14
69
|
scimToken := os.Getenv("SSO_ID_SCIM_BEARER_TOKEN")
|
|
70
|
+
|
|
15
71
|
var mu sync.RWMutex
|
|
16
72
|
scimUsers := map[string]map[string]any{}
|
|
17
73
|
scimGroups := map[string]map[string]any{}
|
|
@@ -26,8 +82,17 @@ func main() {
|
|
|
26
82
|
}
|
|
27
83
|
|
|
28
84
|
mux := http.NewServeMux()
|
|
29
|
-
mux.HandleFunc("/
|
|
30
|
-
|
|
85
|
+
mux.HandleFunc("/api/organizations", func(w http.ResponseWriter, r *http.Request) {
|
|
86
|
+
proxyMgmt(w, r, domain, clientID, clientSecret, apiBase, "/api/organizations")
|
|
87
|
+
})
|
|
88
|
+
mux.HandleFunc("/api/organization-units", func(w http.ResponseWriter, r *http.Request) {
|
|
89
|
+
proxyMgmt(w, r, domain, clientID, clientSecret, apiBase, "/api/organization-units")
|
|
90
|
+
})
|
|
91
|
+
mux.HandleFunc("/api/users", func(w http.ResponseWriter, r *http.Request) {
|
|
92
|
+
proxyMgmt(w, r, domain, clientID, clientSecret, apiBase, "/api/users")
|
|
93
|
+
})
|
|
94
|
+
mux.HandleFunc("/api/groups", func(w http.ResponseWriter, r *http.Request) {
|
|
95
|
+
proxyMgmt(w, r, domain, clientID, clientSecret, apiBase, "/api/groups")
|
|
31
96
|
})
|
|
32
97
|
|
|
33
98
|
mux.HandleFunc("/scim/v2/Users", func(w http.ResponseWriter, r *http.Request) {
|
|
@@ -106,7 +171,6 @@ func main() {
|
|
|
106
171
|
if port == "" {
|
|
107
172
|
port = "8080"
|
|
108
173
|
}
|
|
109
|
-
log.Printf("SSO.ID Go + SCIM starter listening on :%s", port)
|
|
174
|
+
log.Printf("SSO.ID Go + SCIM + Management starter listening on :%s", port)
|
|
110
175
|
log.Fatal(http.ListenAndServe(":"+port, mux))
|
|
111
176
|
}
|
|
112
|
-
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import React, { useState } from 'react';
|
|
2
|
-
import { Button, SafeAreaView, ScrollView, Text, View } from 'react-native';
|
|
2
|
+
import { Button, SafeAreaView, ScrollView, Text, TextInput, View } from 'react-native';
|
|
3
3
|
import { SsoIdMobileClient } from '@sso-id/react-native';
|
|
4
4
|
|
|
5
5
|
const sso = new SsoIdMobileClient({
|
|
@@ -8,38 +8,64 @@ const sso = new SsoIdMobileClient({
|
|
|
8
8
|
redirectUri: 'com.acme.app://callback',
|
|
9
9
|
});
|
|
10
10
|
|
|
11
|
+
const API_BASE = 'http://localhost:4000';
|
|
12
|
+
|
|
11
13
|
export default function App() {
|
|
12
14
|
const [status, setStatus] = useState('Not signed in');
|
|
13
|
-
const [
|
|
15
|
+
const [tab, setTab] = useState<'organizations' | 'organization-units' | 'users' | 'groups' | 'scim'>('organizations');
|
|
16
|
+
const [name, setName] = useState('');
|
|
17
|
+
const [result, setResult] = useState<unknown>(null);
|
|
14
18
|
|
|
15
|
-
async function
|
|
16
|
-
const res = await fetch(
|
|
17
|
-
|
|
19
|
+
async function apiCall(path: string, method = 'GET', body?: unknown) {
|
|
20
|
+
const res = await fetch(`${API_BASE}${path}`, {
|
|
21
|
+
method,
|
|
22
|
+
headers: { 'Content-Type': 'application/json' },
|
|
23
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
18
24
|
});
|
|
19
|
-
|
|
25
|
+
setResult(await res.json());
|
|
20
26
|
}
|
|
21
27
|
|
|
22
28
|
return (
|
|
23
29
|
<SafeAreaView style={{ flex: 1, padding: 20 }}>
|
|
24
30
|
<ScrollView>
|
|
25
|
-
<Text style={{ fontSize: 20, fontWeight: '700', marginBottom:
|
|
31
|
+
<Text style={{ fontSize: 20, fontWeight: '700', marginBottom: 8 }}>SSO.ID React Native Starter</Text>
|
|
26
32
|
<Text style={{ marginBottom: 12 }}>{status}</Text>
|
|
27
|
-
<
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
33
|
+
<Button
|
|
34
|
+
title="Sign In with SSO.ID (OIDC + PKCE)"
|
|
35
|
+
onPress={async () => {
|
|
36
|
+
const { url } = await sso.buildAuthorizeUrl();
|
|
37
|
+
setStatus(`Authorize URL ready: ${url}`);
|
|
38
|
+
}}
|
|
39
|
+
/>
|
|
40
|
+
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 8, marginVertical: 14 }}>
|
|
41
|
+
{(['organizations', 'organization-units', 'users', 'groups', 'scim'] as const).map((t) => (
|
|
42
|
+
<Button
|
|
43
|
+
key={t}
|
|
44
|
+
title={t}
|
|
45
|
+
onPress={() => {
|
|
46
|
+
setTab(t);
|
|
47
|
+
void apiCall(t === 'scim' ? '/api/scim/events' : `/api/${t}`);
|
|
48
|
+
}}
|
|
49
|
+
/>
|
|
50
|
+
))}
|
|
39
51
|
</View>
|
|
40
|
-
|
|
52
|
+
<TextInput
|
|
53
|
+
value={name}
|
|
54
|
+
onChangeText={setName}
|
|
55
|
+
placeholder="Name or email"
|
|
56
|
+
style={{ borderWidth: 1, borderColor: '#cbd5e1', padding: 8, borderRadius: 6, marginBottom: 8 }}
|
|
57
|
+
/>
|
|
58
|
+
<Button
|
|
59
|
+
title={`Create ${tab}`}
|
|
60
|
+
onPress={() => {
|
|
61
|
+
const path = tab === 'scim' ? '/api/scim/push-user' : `/api/${tab}`;
|
|
62
|
+
const payload = tab === 'users' || tab === 'scim' ? { email: name, userName: name, displayName: name } : { name };
|
|
63
|
+
void apiCall(path, 'POST', payload);
|
|
64
|
+
setName('');
|
|
65
|
+
}}
|
|
66
|
+
/>
|
|
67
|
+
{result && <Text style={{ marginTop: 16, fontFamily: 'monospace' }}>{JSON.stringify(result, null, 2)}</Text>}
|
|
41
68
|
</ScrollView>
|
|
42
69
|
</SafeAreaView>
|
|
43
70
|
);
|
|
44
71
|
}
|
|
45
|
-
|
|
@@ -1,14 +1,52 @@
|
|
|
1
1
|
<?php
|
|
2
2
|
declare(strict_types=1);
|
|
3
3
|
|
|
4
|
-
header('Content-Type: application/
|
|
4
|
+
header('Content-Type: application/json');
|
|
5
5
|
|
|
6
6
|
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
|
|
7
7
|
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
|
|
8
|
+
$domain = rtrim(getenv('SSO_ID_DOMAIN') ?: 'acme.sso.id', '/');
|
|
9
|
+
$clientId = getenv('SSO_ID_CLIENT_ID') ?: '';
|
|
10
|
+
$clientSecret = getenv('SSO_ID_CLIENT_SECRET') ?: '';
|
|
11
|
+
$apiBase = rtrim(getenv('SSO_ID_API_BASE_URL') ?: 'https://api.sso.id', '/');
|
|
8
12
|
$scimToken = getenv('SSO_ID_SCIM_BEARER_TOKEN') ?: '';
|
|
9
13
|
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
|
|
10
14
|
|
|
15
|
+
function getM2MToken(string $domain, string $clientId, string $clientSecret): string {
|
|
16
|
+
$base = str_starts_with($domain, 'http') ? $domain : "https://{$domain}";
|
|
17
|
+
$ctx = stream_context_create([
|
|
18
|
+
'http' => [
|
|
19
|
+
'method' => 'POST',
|
|
20
|
+
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
|
|
21
|
+
'content' => http_build_query([
|
|
22
|
+
'grant_type' => 'client_credentials',
|
|
23
|
+
'client_id' => $clientId,
|
|
24
|
+
'client_secret' => $clientSecret,
|
|
25
|
+
]),
|
|
26
|
+
],
|
|
27
|
+
]);
|
|
28
|
+
$raw = file_get_contents("{$base}/auth/oauth/token", false, $ctx);
|
|
29
|
+
$doc = json_decode($raw ?: '{}', true);
|
|
30
|
+
return $doc['access_token'] ?? '';
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (in_array($path, ['/api/organizations', '/api/organization-units', '/api/users', '/api/groups'], true)) {
|
|
34
|
+
$token = getM2MToken($domain, $clientId, $clientSecret);
|
|
35
|
+
$body = file_get_contents('php://input') ?: '';
|
|
36
|
+
$ctx = stream_context_create([
|
|
37
|
+
'http' => [
|
|
38
|
+
'method' => $method,
|
|
39
|
+
'header' => "Authorization: Bearer {$token}\r\nContent-Type: application/json\r\n",
|
|
40
|
+
'content' => $method === 'POST' ? $body : '',
|
|
41
|
+
'ignore_errors' => true,
|
|
42
|
+
],
|
|
43
|
+
]);
|
|
44
|
+
echo file_get_contents("{$apiBase}{$path}", false, $ctx);
|
|
45
|
+
exit;
|
|
46
|
+
}
|
|
47
|
+
|
|
11
48
|
if (str_starts_with($path, '/scim/v2')) {
|
|
49
|
+
header('Content-Type: application/scim+json');
|
|
12
50
|
$provided = str_starts_with($authHeader, 'Bearer ') ? trim(substr($authHeader, 7)) : '';
|
|
13
51
|
if ($scimToken === '' || !hash_equals($scimToken, $provided)) {
|
|
14
52
|
http_response_code(401);
|
|
@@ -16,12 +54,12 @@ if (str_starts_with($path, '/scim/v2')) {
|
|
|
16
54
|
exit;
|
|
17
55
|
}
|
|
18
56
|
|
|
19
|
-
if ($path
|
|
57
|
+
if (in_array($path, ['/scim/v2/Users', '/scim/v2/Groups'], true) && $method === 'GET') {
|
|
20
58
|
echo json_encode(['schemas' => ['urn:ietf:params:scim:api:messages:2.0:ListResponse'], 'totalResults' => 0, 'Resources' => []]);
|
|
21
59
|
exit;
|
|
22
60
|
}
|
|
23
61
|
|
|
24
|
-
if ($path
|
|
62
|
+
if (in_array($path, ['/scim/v2/Users', '/scim/v2/Groups'], true) && $method === 'POST') {
|
|
25
63
|
$payload = json_decode(file_get_contents('php://input') ?: '{}', true) ?? [];
|
|
26
64
|
$payload['id'] = $payload['id'] ?? bin2hex(random_bytes(8));
|
|
27
65
|
http_response_code(201);
|
|
@@ -30,5 +68,4 @@ if (str_starts_with($path, '/scim/v2')) {
|
|
|
30
68
|
}
|
|
31
69
|
}
|
|
32
70
|
|
|
33
|
-
echo json_encode(['status' => 'SSO.ID PHP + SCIM 2.0 Starter Ready']);
|
|
34
|
-
|
|
71
|
+
echo json_encode(['status' => 'SSO.ID PHP + Management API + SCIM 2.0 Starter Ready']);
|
|
@@ -4,20 +4,24 @@ import uuid
|
|
|
4
4
|
from datetime import datetime, timezone
|
|
5
5
|
from fastapi import Depends, FastAPI, Header, HTTPException, Request
|
|
6
6
|
import httpx
|
|
7
|
+
import jwt
|
|
8
|
+
from jwt import PyJWKClient
|
|
7
9
|
from dotenv import load_dotenv
|
|
8
|
-
from sso_id.jwt import verify_access_token
|
|
9
10
|
|
|
10
11
|
load_dotenv()
|
|
11
12
|
|
|
12
13
|
app = FastAPI(title="SSO.ID FastAPI + SCIM 2.0 + Management Starter")
|
|
13
14
|
|
|
14
|
-
DOMAIN = os.getenv("SSO_ID_DOMAIN", "acme.sso.id")
|
|
15
|
+
DOMAIN = os.getenv("SSO_ID_DOMAIN", "acme.sso.id").rstrip("/")
|
|
16
|
+
AUTHORITY = DOMAIN if DOMAIN.startswith("http") else f"https://{DOMAIN}"
|
|
15
17
|
CLIENT_ID = os.getenv("SSO_ID_CLIENT_ID", "")
|
|
16
18
|
CLIENT_SECRET = os.getenv("SSO_ID_CLIENT_SECRET", "")
|
|
17
19
|
API_BASE = os.getenv("SSO_ID_API_BASE_URL", "https://api.sso.id").rstrip("/")
|
|
18
20
|
AUDIENCE = os.getenv("SSO_ID_AUDIENCE") or None
|
|
19
21
|
SCIM_TOKEN = os.getenv("SSO_ID_SCIM_BEARER_TOKEN", "")
|
|
20
22
|
|
|
23
|
+
jwks_client = PyJWKClient(f"{AUTHORITY}/auth/.well-known/jwks.json")
|
|
24
|
+
|
|
21
25
|
scim_users: dict[str, dict] = {}
|
|
22
26
|
scim_groups: dict[str, dict] = {}
|
|
23
27
|
scim_events: list[dict] = []
|
|
@@ -26,7 +30,15 @@ scim_events: list[dict] = []
|
|
|
26
30
|
def require_jwt(authorization: str = Header(default="")):
|
|
27
31
|
if not authorization.startswith("Bearer "):
|
|
28
32
|
raise HTTPException(status_code=401, detail="Missing Bearer token")
|
|
29
|
-
|
|
33
|
+
token = authorization[7:].strip()
|
|
34
|
+
signing_key = jwks_client.get_signing_key_from_jwt(token)
|
|
35
|
+
return jwt.decode(
|
|
36
|
+
token,
|
|
37
|
+
signing_key.key,
|
|
38
|
+
algorithms=["RS256"],
|
|
39
|
+
audience=AUDIENCE,
|
|
40
|
+
options={"verify_aud": bool(AUDIENCE)},
|
|
41
|
+
)
|
|
30
42
|
|
|
31
43
|
|
|
32
44
|
def require_scim(authorization: str = Header(default="")):
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import 'dotenv/config';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import express from 'express';
|
|
4
|
+
import cors from 'cors';
|
|
5
|
+
import { createServer as createViteServer } from 'vite';
|
|
6
|
+
import {
|
|
7
|
+
ManagementClient,
|
|
8
|
+
verifyScimBearerToken,
|
|
9
|
+
formatScimListResponse,
|
|
10
|
+
formatScimError,
|
|
11
|
+
SCIM_CORE_USER_SCHEMA,
|
|
12
|
+
SCIM_CORE_GROUP_SCHEMA,
|
|
13
|
+
} from '@sso-id/node';
|
|
14
|
+
|
|
15
|
+
const app = express();
|
|
16
|
+
app.use(cors());
|
|
17
|
+
app.use(express.json({ type: ['application/json', 'application/scim+json'] }));
|
|
18
|
+
|
|
19
|
+
const mgmt = new ManagementClient({
|
|
20
|
+
domain: process.env.SSO_ID_DOMAIN || process.env.VITE_SSO_ID_DOMAIN || 'acme.sso.id',
|
|
21
|
+
clientId: process.env.SSO_ID_M2M_CLIENT_ID || process.env.SSO_ID_CLIENT_ID || process.env.VITE_SSO_ID_CLIENT_ID || '',
|
|
22
|
+
clientSecret: process.env.SSO_ID_M2M_CLIENT_SECRET || process.env.SSO_ID_CLIENT_SECRET || '',
|
|
23
|
+
apiBaseUrl: process.env.SSO_ID_API_BASE_URL || 'https://api.sso.id',
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
app.get('/api/organizations', async (_req, res) => {
|
|
27
|
+
try { res.json(await mgmt.organizations.list()); } catch (e) { res.status(500).json({ error: e.message }); }
|
|
28
|
+
});
|
|
29
|
+
app.post('/api/organizations', async (req, res) => {
|
|
30
|
+
try { res.status(201).json(await mgmt.organizations.create(req.body)); } catch (e) { res.status(500).json({ error: e.message }); }
|
|
31
|
+
});
|
|
32
|
+
app.get('/api/organization-units', async (req, res) => {
|
|
33
|
+
try {
|
|
34
|
+
const orgId = req.query.organizationId;
|
|
35
|
+
res.json(orgId ? await mgmt.organizationUnits.listByOrganization(String(orgId)) : await mgmt.organizationUnits.list());
|
|
36
|
+
} catch (e) { res.status(500).json({ error: e.message }); }
|
|
37
|
+
});
|
|
38
|
+
app.post('/api/organization-units', async (req, res) => {
|
|
39
|
+
try { res.status(201).json(await mgmt.organizationUnits.create(req.body)); } catch (e) { res.status(500).json({ error: e.message }); }
|
|
40
|
+
});
|
|
41
|
+
app.get('/api/users', async (_req, res) => {
|
|
42
|
+
try { res.json(await mgmt.users.list({ page: 1, pageSize: 50 })); } catch (e) { res.status(500).json({ error: e.message }); }
|
|
43
|
+
});
|
|
44
|
+
app.post('/api/users', async (req, res) => {
|
|
45
|
+
try { res.status(201).json(await mgmt.users.create(req.body)); } catch (e) { res.status(500).json({ error: e.message }); }
|
|
46
|
+
});
|
|
47
|
+
app.get('/api/groups', async (_req, res) => {
|
|
48
|
+
try { res.json(await mgmt.groups.list()); } catch (e) { res.status(500).json({ error: e.message }); }
|
|
49
|
+
});
|
|
50
|
+
app.post('/api/groups', async (req, res) => {
|
|
51
|
+
try { res.status(201).json(await mgmt.groups.create(req.body)); } catch (e) { res.status(500).json({ error: e.message }); }
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
const scimUsers = new Map();
|
|
55
|
+
const scimGroups = new Map();
|
|
56
|
+
const scimEvents = [];
|
|
57
|
+
|
|
58
|
+
function requireScim(req, res, next) {
|
|
59
|
+
if (!verifyScimBearerToken(req.headers.authorization, process.env.SSO_ID_SCIM_BEARER_TOKEN || '')) {
|
|
60
|
+
return res.status(401).json(formatScimError('Unauthorized SCIM request', 401));
|
|
61
|
+
}
|
|
62
|
+
return next();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
app.get('/scim/v2/Users', requireScim, (_req, res) => res.json(formatScimListResponse(Array.from(scimUsers.values()))));
|
|
66
|
+
app.post('/scim/v2/Users', requireScim, (req, res) => {
|
|
67
|
+
const id = req.body.id || randomUUID();
|
|
68
|
+
const u = { schemas: [SCIM_CORE_USER_SCHEMA], active: true, ...req.body, id };
|
|
69
|
+
scimUsers.set(id, u);
|
|
70
|
+
scimEvents.unshift({ type: 'User', op: 'CREATE', id, userName: u.userName, at: new Date().toISOString() });
|
|
71
|
+
res.status(201).json(u);
|
|
72
|
+
});
|
|
73
|
+
app.get('/scim/v2/Groups', requireScim, (_req, res) => res.json(formatScimListResponse(Array.from(scimGroups.values()))));
|
|
74
|
+
app.post('/scim/v2/Groups', requireScim, (req, res) => {
|
|
75
|
+
const id = req.body.id || randomUUID();
|
|
76
|
+
const g = { schemas: [SCIM_CORE_GROUP_SCHEMA], members: [], ...req.body, id };
|
|
77
|
+
scimGroups.set(id, g);
|
|
78
|
+
scimEvents.unshift({ type: 'Group', op: 'CREATE', id, displayName: g.displayName, at: new Date().toISOString() });
|
|
79
|
+
res.status(201).json(g);
|
|
80
|
+
});
|
|
81
|
+
app.get('/api/scim/events', (_req, res) => res.json({ users: Array.from(scimUsers.values()), groups: Array.from(scimGroups.values()), events: scimEvents }));
|
|
82
|
+
app.post('/api/scim/push-user', async (req, res) => {
|
|
83
|
+
try {
|
|
84
|
+
const scim = mgmt.scim.forConnection(process.env.SSO_ID_SCIM_CONNECTION_ID || undefined);
|
|
85
|
+
res.status(201).json(await scim.createUser({ schemas: [SCIM_CORE_USER_SCHEMA], userName: req.body.userName, displayName: req.body.displayName, active: true }));
|
|
86
|
+
} catch (e) { res.status(500).json({ error: e.message }); }
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
app.listen(4000, async () => {
|
|
90
|
+
console.log('SSO.ID Management & SCIM 2.0 API running on http://localhost:4000');
|
|
91
|
+
const vite = await createViteServer({ server: { port: 5173 } });
|
|
92
|
+
await vite.listen();
|
|
93
|
+
vite.printUrls();
|
|
94
|
+
});
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
|
+
<title>SSO.ID React Starter — Auth, Orgs, OUs, Users, Groups & SCIM 2.0</title>
|
|
7
|
+
</head>
|
|
8
|
+
<body style="margin:0;background:#f8fafc;color:#0f172a">
|
|
9
|
+
<div id="root"></div>
|
|
10
|
+
<script type="module" src="/src/main.tsx"></script>
|
|
11
|
+
</body>
|
|
12
|
+
</html>
|
|
@@ -4,13 +4,17 @@
|
|
|
4
4
|
"private": true,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"scripts": {
|
|
7
|
-
"dev": "
|
|
7
|
+
"dev": "node dev.mjs",
|
|
8
8
|
"build": "tsc && vite build",
|
|
9
9
|
"preview": "vite preview"
|
|
10
10
|
},
|
|
11
11
|
"dependencies": {
|
|
12
|
+
"@sso-id/node": "^0.2.0",
|
|
12
13
|
"@sso-id/react": "^0.1.0",
|
|
13
14
|
"@sso-id/ui": "^0.1.0",
|
|
15
|
+
"cors": "^2.8.5",
|
|
16
|
+
"dotenv": "^16.4.5",
|
|
17
|
+
"express": "^4.21.0",
|
|
14
18
|
"react": "^18.3.1",
|
|
15
19
|
"react-dom": "^18.3.1"
|
|
16
20
|
},
|
|
@@ -22,4 +26,3 @@
|
|
|
22
26
|
"vite": "^5.4.0"
|
|
23
27
|
}
|
|
24
28
|
}
|
|
25
|
-
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2022",
|
|
4
|
+
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
|
5
|
+
"module": "ESNext",
|
|
6
|
+
"moduleResolution": "bundler",
|
|
7
|
+
"jsx": "react-jsx",
|
|
8
|
+
"strict": true,
|
|
9
|
+
"noEmit": true,
|
|
10
|
+
"skipLibCheck": true
|
|
11
|
+
},
|
|
12
|
+
"include": ["src"]
|
|
13
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { defineConfig } from 'vite';
|
|
2
|
+
import react from '@vitejs/plugin-react';
|
|
3
|
+
|
|
4
|
+
export default defineConfig({
|
|
5
|
+
plugins: [react()],
|
|
6
|
+
server: {
|
|
7
|
+
port: 5173,
|
|
8
|
+
proxy: {
|
|
9
|
+
'/api': 'http://localhost:4000',
|
|
10
|
+
'/scim': 'http://localhost:4000',
|
|
11
|
+
},
|
|
12
|
+
},
|
|
13
|
+
});
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import 'dotenv/config';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import express from 'express';
|
|
4
|
+
import cors from 'cors';
|
|
5
|
+
import { createServer as createViteServer } from 'vite';
|
|
6
|
+
import {
|
|
7
|
+
ManagementClient,
|
|
8
|
+
verifyScimBearerToken,
|
|
9
|
+
formatScimListResponse,
|
|
10
|
+
formatScimError,
|
|
11
|
+
SCIM_CORE_USER_SCHEMA,
|
|
12
|
+
SCIM_CORE_GROUP_SCHEMA,
|
|
13
|
+
} from '@sso-id/node';
|
|
14
|
+
|
|
15
|
+
const app = express();
|
|
16
|
+
app.use(cors());
|
|
17
|
+
app.use(express.json({ type: ['application/json', 'application/scim+json'] }));
|
|
18
|
+
|
|
19
|
+
const mgmt = new ManagementClient({
|
|
20
|
+
domain: process.env.SSO_ID_DOMAIN || process.env.VITE_SSO_ID_DOMAIN || 'acme.sso.id',
|
|
21
|
+
clientId: process.env.SSO_ID_M2M_CLIENT_ID || process.env.SSO_ID_CLIENT_ID || process.env.VITE_SSO_ID_CLIENT_ID || '',
|
|
22
|
+
clientSecret: process.env.SSO_ID_M2M_CLIENT_SECRET || process.env.SSO_ID_CLIENT_SECRET || '',
|
|
23
|
+
apiBaseUrl: process.env.SSO_ID_API_BASE_URL || 'https://api.sso.id',
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
app.get('/api/organizations', async (_req, res) => {
|
|
27
|
+
try { res.json(await mgmt.organizations.list()); } catch (e) { res.status(500).json({ error: e.message }); }
|
|
28
|
+
});
|
|
29
|
+
app.post('/api/organizations', async (req, res) => {
|
|
30
|
+
try { res.status(201).json(await mgmt.organizations.create(req.body)); } catch (e) { res.status(500).json({ error: e.message }); }
|
|
31
|
+
});
|
|
32
|
+
app.get('/api/organization-units', async (req, res) => {
|
|
33
|
+
try {
|
|
34
|
+
const orgId = req.query.organizationId;
|
|
35
|
+
res.json(orgId ? await mgmt.organizationUnits.listByOrganization(String(orgId)) : await mgmt.organizationUnits.list());
|
|
36
|
+
} catch (e) { res.status(500).json({ error: e.message }); }
|
|
37
|
+
});
|
|
38
|
+
app.post('/api/organization-units', async (req, res) => {
|
|
39
|
+
try { res.status(201).json(await mgmt.organizationUnits.create(req.body)); } catch (e) { res.status(500).json({ error: e.message }); }
|
|
40
|
+
});
|
|
41
|
+
app.get('/api/users', async (_req, res) => {
|
|
42
|
+
try { res.json(await mgmt.users.list({ page: 1, pageSize: 50 })); } catch (e) { res.status(500).json({ error: e.message }); }
|
|
43
|
+
});
|
|
44
|
+
app.post('/api/users', async (req, res) => {
|
|
45
|
+
try { res.status(201).json(await mgmt.users.create(req.body)); } catch (e) { res.status(500).json({ error: e.message }); }
|
|
46
|
+
});
|
|
47
|
+
app.get('/api/groups', async (_req, res) => {
|
|
48
|
+
try { res.json(await mgmt.groups.list()); } catch (e) { res.status(500).json({ error: e.message }); }
|
|
49
|
+
});
|
|
50
|
+
app.post('/api/groups', async (req, res) => {
|
|
51
|
+
try { res.status(201).json(await mgmt.groups.create(req.body)); } catch (e) { res.status(500).json({ error: e.message }); }
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
const scimUsers = new Map();
|
|
55
|
+
const scimGroups = new Map();
|
|
56
|
+
const scimEvents = [];
|
|
57
|
+
|
|
58
|
+
function requireScim(req, res, next) {
|
|
59
|
+
if (!verifyScimBearerToken(req.headers.authorization, process.env.SSO_ID_SCIM_BEARER_TOKEN || '')) {
|
|
60
|
+
return res.status(401).json(formatScimError('Unauthorized SCIM request', 401));
|
|
61
|
+
}
|
|
62
|
+
return next();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
app.get('/scim/v2/Users', requireScim, (_req, res) => res.json(formatScimListResponse(Array.from(scimUsers.values()))));
|
|
66
|
+
app.post('/scim/v2/Users', requireScim, (req, res) => {
|
|
67
|
+
const id = req.body.id || randomUUID();
|
|
68
|
+
const u = { schemas: [SCIM_CORE_USER_SCHEMA], active: true, ...req.body, id };
|
|
69
|
+
scimUsers.set(id, u);
|
|
70
|
+
scimEvents.unshift({ type: 'User', op: 'CREATE', id, userName: u.userName, at: new Date().toISOString() });
|
|
71
|
+
res.status(201).json(u);
|
|
72
|
+
});
|
|
73
|
+
app.get('/scim/v2/Groups', requireScim, (_req, res) => res.json(formatScimListResponse(Array.from(scimGroups.values()))));
|
|
74
|
+
app.post('/scim/v2/Groups', requireScim, (req, res) => {
|
|
75
|
+
const id = req.body.id || randomUUID();
|
|
76
|
+
const g = { schemas: [SCIM_CORE_GROUP_SCHEMA], members: [], ...req.body, id };
|
|
77
|
+
scimGroups.set(id, g);
|
|
78
|
+
scimEvents.unshift({ type: 'Group', op: 'CREATE', id, displayName: g.displayName, at: new Date().toISOString() });
|
|
79
|
+
res.status(201).json(g);
|
|
80
|
+
});
|
|
81
|
+
app.get('/api/scim/events', (_req, res) => res.json({ users: Array.from(scimUsers.values()), groups: Array.from(scimGroups.values()), events: scimEvents }));
|
|
82
|
+
app.post('/api/scim/push-user', async (req, res) => {
|
|
83
|
+
try {
|
|
84
|
+
const scim = mgmt.scim.forConnection(process.env.SSO_ID_SCIM_CONNECTION_ID || undefined);
|
|
85
|
+
res.status(201).json(await scim.createUser({ schemas: [SCIM_CORE_USER_SCHEMA], userName: req.body.userName, displayName: req.body.displayName, active: true }));
|
|
86
|
+
} catch (e) { res.status(500).json({ error: e.message }); }
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
app.listen(4000, async () => {
|
|
90
|
+
console.log('SSO.ID Management & SCIM 2.0 API running on http://localhost:4000');
|
|
91
|
+
const vite = await createViteServer({ server: { port: 5173 } });
|
|
92
|
+
await vite.listen();
|
|
93
|
+
vite.printUrls();
|
|
94
|
+
});
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
|
+
<title>SSO.ID Vue 3 Starter — Auth, Orgs, OUs, Users, Groups & SCIM 2.0</title>
|
|
7
|
+
</head>
|
|
8
|
+
<body style="margin:0;background:#f8fafc;color:#0f172a">
|
|
9
|
+
<div id="app"></div>
|
|
10
|
+
<script type="module" src="/src/main.ts"></script>
|
|
11
|
+
</body>
|
|
12
|
+
</html>
|
|
@@ -4,11 +4,15 @@
|
|
|
4
4
|
"private": true,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"scripts": {
|
|
7
|
-
"dev": "
|
|
7
|
+
"dev": "node dev.mjs",
|
|
8
8
|
"build": "vite build"
|
|
9
9
|
},
|
|
10
10
|
"dependencies": {
|
|
11
|
+
"@sso-id/node": "^0.2.0",
|
|
11
12
|
"@sso-id/vue": "^0.1.0",
|
|
13
|
+
"cors": "^2.8.5",
|
|
14
|
+
"dotenv": "^16.4.5",
|
|
15
|
+
"express": "^4.21.0",
|
|
12
16
|
"vue": "^3.5.0"
|
|
13
17
|
},
|
|
14
18
|
"devDependencies": {
|
|
@@ -17,4 +21,3 @@
|
|
|
17
21
|
"vite": "^5.4.0"
|
|
18
22
|
}
|
|
19
23
|
}
|
|
20
|
-
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { defineConfig } from 'vite';
|
|
2
|
+
import vue from '@vitejs/plugin-vue';
|
|
3
|
+
|
|
4
|
+
export default defineConfig({
|
|
5
|
+
plugins: [vue()],
|
|
6
|
+
server: {
|
|
7
|
+
port: 5173,
|
|
8
|
+
proxy: {
|
|
9
|
+
'/api': 'http://localhost:4000',
|
|
10
|
+
'/scim': 'http://localhost:4000',
|
|
11
|
+
},
|
|
12
|
+
},
|
|
13
|
+
});
|