Skip to content

Commit b7dfd2a

Browse files
authored
Simplify verification in nodes with jose
This switches the verification from using jsonwebtoken and other libraries to using Jose. The verification step is simpler and the keys are automatically selected.
1 parent 35b3b01 commit b7dfd2a

File tree

1 file changed

+16
-25
lines changed

1 file changed

+16
-25
lines changed

src/content/docs/cloudflare-one/identity/authorization-cookie/validating-json.mdx

Lines changed: 16 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -252,9 +252,7 @@ if __name__ == '__main__':
252252

253253
```javascript
254254
const express = require('express');
255-
const cookieParser = require('cookie-parser');
256-
const jwksClient = require('jwks-rsa');
257-
const jwt = require('jsonwebtoken');
255+
const jose = require('jose');
258256

259257
// The Application Audience (AUD) tag for your application
260258
const AUD = process.env.POLICY_AUD;
@@ -263,44 +261,37 @@ const AUD = process.env.POLICY_AUD;
263261
const TEAM_DOMAIN = process.env.TEAM_DOMAIN;
264262
const CERTS_URL = `${TEAM_DOMAIN}/cdn-cgi/access/certs`;
265263

266-
const client = jwksClient({
267-
jwksUri: CERTS_URL
268-
});
269-
270-
const getKey = (header, callback) => {
271-
client.getSigningKey(header.kid, function(err, key) {
272-
callback(err, key?.getPublicKey());
273-
});
274-
}
264+
const JWKS = jose.createRemoteJWKSet(new URL(CERTS_URL));
275265

276266
// verifyToken is a middleware to verify a CF authorization token
277-
const verifyToken = (req, res, next) => {
278-
const token = req.cookies['CF_Authorization'];
267+
const verifyToken = async (req, res, next) => {
268+
const token = req.headers['cf-access-jwt-assertion'];
279269

280270
// Make sure that the incoming request has our token header
281271
if (!token) {
282-
return res.status(403).send({ status: false, message: 'missing required cf authorization token' });
272+
return res.status(403).send({
273+
status: false,
274+
message: 'missing required cf authorization token',
275+
});
283276
}
284277

285-
jwt.verify(token, getKey, { audience: AUD }, (err, decoded) => {
286-
if (err) {
287-
return res.status(403).send({ status: false, message: 'invalid token' });
288-
}
289-
290-
req.user = decoded;
291-
next();
278+
const result = await jose.jwtVerify(token, JWKS, {
279+
issuer: TEAM_DOMAIN,
280+
audience: AUD,
292281
});
293-
}
282+
283+
req.user = result.payload;
284+
next();
285+
};
294286

295287
const app = express();
296288

297-
app.use(cookieParser());
298289
app.use(verifyToken);
299290

300291
app.get('/', (req, res) => {
301292
res.send('Hello World!');
302293
});
303294

304-
app.listen(3333)
295+
app.listen(3333);
305296

306297
```

0 commit comments

Comments
 (0)