-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnodejs_example.js
More file actions
300 lines (258 loc) · 8.56 KB
/
nodejs_example.js
File metadata and controls
300 lines (258 loc) · 8.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
const express = require("express");
const axios = require("axios");
const sqlite3 = require("sqlite3").verbose();
const crypto = require("crypto");
const jwt = require("jsonwebtoken");
const session = require("express-session");
const jwkToPem = require("jwk-to-pem");
const app = express();
const db = new sqlite3.Database(":memory:");
// Configure session middleware
app.use(
session({
secret: process.env.SESSION_SECRET || "oidc-example-secret",
resave: false,
saveUninitialized: true,
})
);
// Initialize database
db.serialize(() => {
db.run(
"CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, email TEXT)"
);
db.run(
"CREATE TABLE federated_credentials (user_id INTEGER, provider TEXT, subject TEXT, PRIMARY KEY (provider, subject))"
);
});
// Configuration
const CLIENT_ID = process.env.OIDC_CLIENT_ID;
const CLIENT_SECRET = process.env.OIDC_CLIENT_SECRET;
const REDIRECT_URI = "https://example.com/oidc/callback";
const ISSUER_URL = "https://accounts.google.com";
// OIDC discovery endpoints cache
let oidcConfig = null;
// Function to fetch OIDC configuration from the discovery endpoint
async function fetchOIDCConfiguration() {
if (oidcConfig) return oidcConfig;
try {
const response = await axios.get(
`${ISSUER_URL}/.well-known/openid-configuration`
);
oidcConfig = response.data;
return oidcConfig;
} catch (error) {
console.error("Failed to fetch OIDC configuration:", error);
throw error;
}
}
// Function to generate and verify PKCE challenge
function generatePKCE() {
// Generate code verifier
const codeVerifier = crypto.randomBytes(32).toString("base64url");
// Generate code challenge (SHA256 hash of verifier, base64url encoded)
const codeChallenge = crypto
.createHash("sha256")
.update(codeVerifier)
.digest("base64")
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=/g, "");
return { codeVerifier, codeChallenge };
}
// Function to fetch JWKS
async function fetchJWKS() {
const config = await fetchOIDCConfiguration();
const response = await axios.get(config.jwks_uri);
return response.data.keys;
}
// Function to verify ID token
async function verifyIdToken(idToken) {
// First, decode the header without verification to get the key ID (kid)
const header = JSON.parse(
Buffer.from(idToken.split(".")[0], "base64url").toString()
);
// Fetch JWKS and find the correct key
const jwks = await fetchJWKS();
const signingKey = jwks.find((key) => key.kid === header.kid);
if (!signingKey) {
throw new Error("Unable to find signing key");
}
// Format key for JWT verification
const publicKey = jwkToPem(signingKey);
return new Promise((resolve, reject) => {
jwt.verify(
idToken,
publicKey,
{
algorithms: [signingKey.alg],
audience: CLIENT_ID,
issuer: ISSUER_URL,
},
(err, decoded) => {
if (err) return reject(err);
resolve(decoded);
}
);
});
}
// OIDC login route
app.get("/login", async (req, res) => {
try {
// Fetch OIDC configuration
const config = await fetchOIDCConfiguration();
// Generate state for CSRF protection
const state = crypto.randomBytes(16).toString("hex");
req.session.state = state;
// Generate nonce for replay protection
const nonce = crypto.randomBytes(16).toString("hex");
req.session.nonce = nonce;
// Generate PKCE code verifier and challenge
const { codeVerifier, codeChallenge } = generatePKCE();
req.session.codeVerifier = codeVerifier;
// Build authorization URL
const authUrl = new URL(config.authorization_endpoint);
authUrl.searchParams.append("client_id", CLIENT_ID);
authUrl.searchParams.append("redirect_uri", REDIRECT_URI);
authUrl.searchParams.append("response_type", "code");
authUrl.searchParams.append("scope", "openid profile email");
authUrl.searchParams.append("state", state);
authUrl.searchParams.append("nonce", nonce);
authUrl.searchParams.append("code_challenge", codeChallenge);
authUrl.searchParams.append("code_challenge_method", "S256");
res.redirect(authUrl.toString());
} catch (error) {
console.error("Login initialization error:", error);
res.status(500).send("Failed to initialize login");
}
});
// OIDC callback route
app.get("/oidc/callback", async (req, res) => {
const { code, state } = req.query;
const { codeVerifier, state: storedState, nonce: storedNonce } = req.session;
// Verify state
if (state !== storedState) {
return res.status(403).send("Invalid state parameter");
}
try {
// Fetch OIDC configuration
const config = await fetchOIDCConfiguration();
// Exchange code for tokens
const tokenResponse = await axios.post(
config.token_endpoint,
new URLSearchParams({
grant_type: "authorization_code",
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
code,
redirect_uri: REDIRECT_URI,
code_verifier: codeVerifier,
}),
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
}
);
const { id_token, access_token } = tokenResponse.data;
// Verify ID token
const claims = await verifyIdToken(id_token);
// Verify nonce
if (claims.nonce !== storedNonce) {
return res.status(403).send("Invalid nonce");
}
// Extract user info from ID token
const { sub: subject, name, email } = claims;
// If we need more user info, we can fetch it from the userinfo endpoint
// const userInfoResponse = await axios.get(config.userinfo_endpoint, {
// headers: { Authorization: `Bearer ${access_token}` }
// });
// const userInfo = userInfoResponse.data;
// Check if user exists in federated_credentials
db.get(
"SELECT * FROM federated_credentials WHERE provider = ? AND subject = ?",
[ISSUER_URL, subject],
(err, cred) => {
if (err) return res.status(500).send("Database error");
if (!cred) {
// New user: create account
db.run(
"INSERT INTO users (name, email) VALUES (?, ?)",
[name, email],
function (err) {
if (err) return res.status(500).send("Database error");
const userId = this.lastID;
db.run(
"INSERT INTO federated_credentials (user_id, provider, subject) VALUES (?, ?, ?)",
[userId, ISSUER_URL, subject],
(err) => {
if (err) return res.status(500).send("Database error");
// Store user info in session
req.session.user = { id: userId, name, email };
res.send(`Logged in as ${name} (${email})`);
}
);
}
);
} else {
// Existing user: fetch and log in
db.get(
"SELECT * FROM users WHERE id = ?",
[cred.user_id],
(err, user) => {
if (err || !user) return res.status(500).send("Database error");
// Store user info in session
req.session.user = {
id: user.id,
name: user.name,
email: user.email,
};
res.send(`Logged in as ${user.name} (${user.email})`);
}
);
}
}
);
} catch (error) {
console.error("OIDC callback error:", error);
res.status(500).send("OIDC authentication error");
}
});
// User info endpoint (requires authentication)
app.get("/userinfo", (req, res) => {
if (!req.session.user) {
return res.status(401).send("Not authenticated");
}
res.json(req.session.user);
});
// Logout endpoint
app.get("/logout", async (req, res) => {
try {
// Fetch OIDC configuration to get end session endpoint
const config = await fetchOIDCConfiguration();
let logoutUrl;
if (config.end_session_endpoint) {
logoutUrl = new URL(config.end_session_endpoint);
logoutUrl.searchParams.append("client_id", CLIENT_ID);
logoutUrl.searchParams.append(
"post_logout_redirect_uri",
"https://example.com"
);
}
// Clear the session
req.session.destroy(() => {
if (logoutUrl) {
res.redirect(logoutUrl.toString());
} else {
res.redirect("/");
}
});
} catch (error) {
console.error("Logout error:", error);
// Even if there's an error fetching the config,
// still clear the session and redirect
req.session.destroy(() => {
res.redirect("/");
});
}
});
app.listen(3000, () => console.log("Server running on port 3000"));