-
Notifications
You must be signed in to change notification settings - Fork 210
Open
Description
The code below produces an unexpected result. Providing both the issuer and audience keys in the new JwtStrategy will always produce an HTTP 401 Unauthorized response on a protected API endpoint. Removing these from the JwtStrategy options produces the expected result (HTTP 200).
From the passport-jwt documentation:
issuer: If defined the token issuer (iss) will be verified against this value.
audience: If defined, the token audience (aud) will be verified against this value.
It would makes sense that if the issue and audience are constant, the verification can be expected to succeed.
Please advise!
....
Steps to reproduce:
- Copy the code below into a file called
server.js - In the same directory as server.js, run the following commands:
-
npm init -y
-
npm i --save express passport passport-jwt cookie-parser jsonwebtoken
- Run
node server.js - Navigate to http://localhost:3000/getToken
- Click the link from the /getToken end point to go to the protected endpoint. You will get a 401.
const express = require('express');
const cookieParser = require('cookie-parser');
const jwt = require('jsonwebtoken');
const passport = require('passport');
const JwtStrategy = require("passport-jwt").Strategy;
const app = express();
app.use(cookieParser());
const JWT_SECRET = "qwerty";
const JWT_ISSUER = "myself"
const JWT_AUDIENCE = "everyone"
const API_PORT = 3000
passport.use(new JwtStrategy({
jwtFromRequest: req => req.cookies.jwt,
secretOrKey: JWT_SECRET,
issuer: JWT_ISSUER,
audience: JWT_AUDIENCE,
}, (jwtPayload, callback) => {
let retVal = jwtPayload.subject=="success" ? {message: "Success"} : new Error("Invalid token");
return callback(null, retVal);
})
);
app.get("/getToken", (req, res, next) => {
const token = jwt.sign({
issuer: JWT_ISSUER,
audience: JWT_AUDIENCE,
subject: "success"
},
JWT_SECRET
);
res.cookie("jwt", token);
res.send(`<!DOCTYPE html>
<html>
<head><title>Token</title><head>
<body>
<h1>Your token is</h1>
<p>${token}</p>
<p><a href='/protectedPage'>Go to protected page</a></p>
</body>
</html>
`);
})
app.get("/protectedPage", passport.authenticate('jwt', {session:false}), (req, res, next) => {
res.send(`<!DOCTYPE html>
<html>
<head><title>Token</title><head>
<body>
<h1>Welcome to the protected page</h1>
</body>
</html>
`);
})
app.listen(API_PORT, () => {
console.log(`Express server listening on port ${API_PORT}`)
});
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels