-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPKCEflow.js
More file actions
91 lines (79 loc) · 2.64 KB
/
Copy pathPKCEflow.js
File metadata and controls
91 lines (79 loc) · 2.64 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
const express = require("express");
const {Issuer, generators} = require("openid-client");
const router = express.Router();
const fs = require("fs");
router.use(
express.session({
secret: "your_secret",
resave: false,
saveUninitialized: true,
})
);
const redirectUri = "http://localhost:3000/pkce/callback";
let client;
async function setupClient() {
const issuer = await Issuer.discover(process.Env.ISSUER_URL);
client = new issuer.Client({
client_id: process.env.CLIENT_ID,
redirect_uris: [redirectUri],
response_types: ["code"],
});
}
setupClient().catch(console.error);
router.get("/login", async (req, res) => {
const codeVerifier = generators.codeVerifier();
const codeChallenge = generators.codeChallenge(codeVerifier);
const params = {
scope: "openid email profile",
response_type: "code",
redirect_uri: redirectUri,
code_challenge: codeChallenge,
code_challenge_method: "S256",
};
const authUrl = client.authorizationUrl(params);
// Save the auth request details in the session. Should not expose client_secret to the client.
req.session.authRequestDetails = {
authUrl: authUrl,
params: params,
codeVerifier: codeVerifier,
};
res.redirect(authUrl);
});
router.get("/callback", async (req, res) => {
const params = client.callbackParams(req);
const tokenSet = await client.callback(redirectUri, params, {
code_verifier: req.session.authRequestDetails.codeVerifier,
});
const authCode = params;
const accessToken = tokenSet.access_token;
const scopes = tokenSet.scope;
const authRequestDetails = req.session.authRequestDetails;
const filePath = "./public/page.html";
fs.readFile(filePath, "utf8", (err, data) => {
if (err) {
console.error(err);
return;
}
const result = data.replace("{{oauth-flow}}", "PKCE Flow");
result = result.replace(
"{{authorize-detail}}",
` <h3>Authorization Request Details</h3>
<p><strong>Authorization URL:</strong> ${
authRequestDetails.authUrl
}</p>
<p><strong>Parameters:</strong> ${JSON.stringify(
authRequestDetails.params,
null,
2
)}</p>
<h3>Callback Response</h3>
<p><strong>Authorization Code:</strong> ${authCode}</p>
<p><strong>Access Token:</strong> ${accessToken}</p>
<p><strong>ID Token:</strong> ${tokenSet.id_token}</p>
<p><strong>Scopes:</strong> ${scopes}</p>`
);
// Send the modified HTML to the client
res.send(result);
});
});
module.exports = router;