Skip to content

JwtStrategy always fails to authenticate if issuer and audience are included! #262

@RobbieS82

Description

@RobbieS82

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:

  1. Copy the code below into a file called server.js
  2. In the same directory as server.js, run the following commands:
    1. npm init -y
    1. npm i --save express passport passport-jwt cookie-parser jsonwebtoken
  3. Run node server.js
  4. Navigate to http://localhost:3000/getToken
  5. 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}`)
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions