Giter Club home page Giter Club logo

express-jwt's Introduction

express-jwt

This module provides Express middleware for validating JWTs (JSON Web Tokens) through the jsonwebtoken module. The decoded JWT payload is available on the request object.

Install

$ npm install express-jwt

API

expressjwt(options)

Options has the following parameters:

  • secret: jwt.Secret | GetVerificationKey (required): The secret as a string or a function to retrieve the secret.
  • getToken?: TokenGetter (optional): A function that receives the express Request and returns the token, by default it looks in the Authorization header.
  • isRevoked?: IsRevoked (optional): A function to verify if a token is revoked.
  • onExpired?: ExpirationHandler (optional): A function to handle expired tokens.
  • credentialsRequired?: boolean (optional): If its false, continue to the next middleware if the request does not contain a token instead of failing, defaults to true.
  • requestProperty?: string (optional): Name of the property in the request object where the payload is set. Default to req.auth.
  • Plus... all the options available in the jsonwebtoken verify function.

The available functions have the following interface:

  • GetVerificationKey = (req: express.Request, token: jwt.Jwt | undefined) => Promise<jwt.Secret>;
  • IsRevoked = (req: express.Request, token: jwt.Jwt | undefined) => Promise<boolean>;
  • TokenGetter = (req: express.Request) => string | Promise<string> | undefined;

Usage

Basic usage using an HS256 secret:

var { expressjwt: jwt } = require("express-jwt");
// or ES6
// import { expressjwt, ExpressJwtRequest } from "express-jwt";

app.get(
  "/protected",
  jwt({ secret: "shhhhhhared-secret", algorithms: ["HS256"] }),
  function (req, res) {
    if (!req.auth.admin) return res.sendStatus(401);
    res.sendStatus(200);
  }
);

The decoded JWT payload is available on the request via the auth property.

The default behavior of the module is to extract the JWT from the Authorization header as an OAuth2 Bearer token.

Required Parameters

The algorithms parameter is required to prevent potential downgrade attacks when providing third party libraries as secrets.

⚠️ Do not mix symmetric and asymmetric (ie HS256/RS256) algorithms: Mixing algorithms without further validation can potentially result in downgrade vulnerabilities.

jwt({
  secret: "shhhhhhared-secret",
  algorithms: ["HS256"],
  //algorithms: ['RS256']
});

Additional Options

You can specify audience and/or issuer as well, which is highly recommended for security purposes:

jwt({
  secret: "shhhhhhared-secret",
  audience: "http://myapi/protected",
  issuer: "http://issuer",
  algorithms: ["HS256"],
});

If the JWT has an expiration (exp), it will be checked.

If you are using a base64 URL-encoded secret, pass a Buffer with base64 encoding as the secret instead of a string:

jwt({
  secret: Buffer.from("shhhhhhared-secret", "base64"),
  algorithms: ["RS256"],
});

To only protect specific paths (e.g. beginning with /api), use express router call use, like so:

app.use("/api", jwt({ secret: "shhhhhhared-secret", algorithms: ["HS256"] }));

Or, the other way around, if you want to make some paths unprotected, call unless like so.

app.use(
  jwt({
    secret: "shhhhhhared-secret",
    algorithms: ["HS256"],
  }).unless({ path: ["/token"] })
);

This is especially useful when applying to multiple routes. In the example above, path can be a string, a regexp, or an array of any of those.

For more details on the .unless syntax including additional options, please see express-unless.

This module also support tokens signed with public/private key pairs. Instead of a secret, you can specify a Buffer with the public key

var publicKey = fs.readFileSync("/path/to/public.pub");
jwt({ secret: publicKey, algorithms: ["RS256"] });

Customizing Token Location

A custom function for extracting the token from a request can be specified with the getToken option. This is useful if you need to pass the token through a query parameter or a cookie. You can throw an error in this function and it will be handled by express-jwt.

app.use(
  jwt({
    secret: "hello world !",
    algorithms: ["HS256"],
    credentialsRequired: false,
    getToken: function fromHeaderOrQuerystring(req) {
      if (
        req.headers.authorization &&
        req.headers.authorization.split(" ")[0] === "Bearer"
      ) {
        return req.headers.authorization.split(" ")[1];
      } else if (req.query && req.query.token) {
        return req.query.token;
      }
      return null;
    },
  })
);

Retrieve key dynamically

If you need to obtain the key dynamically from other sources, you can pass a function in the secret parameter with the following parameters:

  • req (Object) - The express request object.
  • token (Object) - An object with the JWT payload and headers.

For example, if the secret varies based on the issuer:

var jwt = require("express-jwt");
var data = require("./data");
var utilities = require("./utilities");

var getSecret = async function (req, token) {
  const issuer = token.payload.iss;
  const tenant = await data.getTenantByIdentifier(issuer);
  if (!tenant) {
    throw new Error("missing_secret");
  }
  return utilities.decrypt(tenant.secret);
};

app.get(
  "/protected",
  jwt({ secret: getSecret, algorithms: ["HS256"] }),
  function (req, res) {
    if (!req.auth.admin) return res.sendStatus(401);
    res.sendStatus(200);
  }
);

Secret rotation

The getSecret callback could also be used in cases where the same issuer might issue tokens with different keys at certain point:

var getSecret = async function (req, token) {
  const { iss } = token.payload;
  const { kid } = token.header;
  // get the verification key by a given key-id and issuer.
  return verificationKey;
};

Revoked tokens

It is possible that some tokens will need to be revoked so they cannot be used any longer. You can provide a function as the isRevoked option. The signature of the function is function(req, payload, done):

  • req (Object) - The express request object.
  • token (Object) - An object with the JWT payload and headers.

For example, if the (iss, jti) claim pair is used to identify a JWT:

const jwt = require("express-jwt");
const data = require("./data");

const isRevokedCallback = async (req, token) => {
  const issuer = token.payload.iss;
  const tokenId = token.payload.jti;
  const token = await data.getRevokedToken(issuer, tokenId);
  return token !== "undefined";
};

app.get(
  "/protected",
  jwt({
    secret: "shhhhhhared-secret",
    algorithms: ["HS256"],
    isRevoked: isRevokedCallback,
  }),
  function (req, res) {
    if (!req.auth.admin) return res.sendStatus(401);
    res.sendStatus(200);
  }
);

Handling expired tokens

You can handle expired tokens as follows:

  jwt({
    secret: "shhhhhhared-secret",
    algorithms: ["HS256"],
    onExpired: async (req, err) => {
      if (new Date() - err.inner.expiredAt < 5000) { return;}
      throw err;
    },,
  })

Error handling

The default behavior is to throw an error when the token is invalid, so you can add your custom logic to manage unauthorized access as follows:

app.use(function (err, req, res, next) {
  if (err.name === "UnauthorizedError") {
    res.status(401).send("invalid token...");
  } else {
    next(err);
  }
});

You might want to use this module to identify registered users while still providing access to unregistered users. You can do this by using the option credentialsRequired:

app.use(
  jwt({
    secret: "hello world !",
    algorithms: ["HS256"],
    credentialsRequired: false,
  })
);

Typescript

A Request type is provided from express-jwt, which extends express.Request with the auth property. It could be aliased, like how JWTRequest is below.

import { expressjwt, Request as JWTRequest } from "express-jwt";

app.get(
  "/protected",
  expressjwt({ secret: "shhhhhhared-secret", algorithms: ["HS256"] }),
  function (req: JWTRequest, res: express.Response) {
    if (!req.auth?.admin) return res.sendStatus(401);
    res.sendStatus(200);
  }
);

Migration from v6

  1. The middleware function is now available as a named import rather than a default one: import { expressjwt } from 'express-jwt'
  2. The decoded JWT payload is now available as req.auth rather than req.user
  3. The secret function had (req, header, payload, cb), now it can return a promise and receives (req, token). token has header and payload.
  4. The isRevoked function had (req, payload, cb), now it can return a promise and receives (req, token). token has header and payload.

Related Modules

Tests

$ npm install
$ npm test

Contributors

Check them out here

Issue Reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

Author

Auth0

License

This project is licensed under the MIT license. See the LICENSE file for more info.

express-jwt's People

Contributors

aarongodin avatar clevasseur avatar crew-security avatar dschenkelman avatar dwmkerr avatar emiljanitzek avatar fanixk avatar geekgonecrazy avatar iamsebastian avatar jaredhanson avatar jfromaniello avatar mcastany avatar mck- avatar michieldemey avatar nklhtv avatar ntotten avatar ohjimijimijimi avatar petetnt avatar philosoralphter avatar pose avatar prophet32j avatar rustybailey avatar scniro avatar seanmcp avatar shane-tomlinson avatar siyangbi avatar timelf123 avatar twistedstream avatar vidstige avatar woloski avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

express-jwt's Issues

UnauthorizedError even when authorized

Hi,

I've got everything working and my application is successfully reading tokens. A passing curiosity however is when I use the following:

app.use(expressJwt({secret : 'secret'}).unless({ path : ['/user/auth']}));

And afterwards have an error handler like this:

app.use(function (err, req, res, next) {
    console.log(err);
});

UnathorizedError is always being thrown.

I did a little digging around in the source and it looks like two calls are being made in succession to middleware. The first is successful and the token is found but subsequently another is made and the 'token' variable never gets set.

Is this a rookie mistake I'm making within my express app? I think that's likely but it'd be good to get some clarity on this for myself and anyone else working with this awesome library.

Note: I'm using Express 4.x - Only happens on Chrome.

Multiple sign() tokens/users on same browser/website page

Hi i followed the example here : http://blog.auth0.com/2014/01/07/angularjs-authentication-with-cookies-vs-token/

Everything works great but i got a strange problem and i don't know how to fix it.

The first time i sign() a user token, everything works great , i can access the protected urls etc.

Then if i logout/remove token and then create a new user and create new token for the new user, protected urls becomes not-accessible.

I checked the token sent and returned both in backend and frontend and everything matches, it's just like i can't sign two or more times with different users tokens but same browser.

i get ----> {"error":{"message":"invalid signature","code":"invalid_token","status":401,"inner":{}}}

While Authorization header is ok and token matches (i checked)

I also opened a stackoverflow question if you can help !

thank you a lot!

http://stackoverflow.com/questions/21904382/node-js-jwt-token-and-logic-behind

Not throwing unauthorized errors

As per your documentation, In the secret callback function I will throw errors. I'm listening for an 'UnauthorizedError' in my middle ware to catch it (also per your documentation). The code on line 100 (index.js) doesn't hijack the error and make it an UnauthorizedError neither does it continue with validation. This allows unauthorized usage.

suggested change:

100: if (err) { return next(err); }

to

100:if(err) { return next(new UnauthorizedError(err))}

How to support refresh tokens

I've been trying to use your angular-jwt module with the express-jwt module to refresh expired tokens. However, the documentation for these two modules does not seem to match up or explain how they work with each other.

I've created an express route /api/auth/refresh where I am attempting to issue a new refreshed token, and I am calling this route from the 'delegated endpoint' feature of angular-jwt. But the following code throws a 'token expired' error and I'm therefore unable to continue and issue the refreshed token:

  // verify the existing token
  var profile = jwt.verify(req.body.token, secret);

I'm reporting this as an issue since the documentation (for both modules) should really explain how they are meant to interoperate, and the documentation here could cover how the refresh is intended to be implemented in Express.

Why not having a callback after token checking?

Hi,
the following is the simple usage example of the documentation:

app.get('/protected',
  jwt({secret: 'shhhhhhared-secret'}),
  function(req, res) {
    if (!req.user.admin) return res.send(401);
    res.send(200);
  });

Of course we can use the module also as a global middleware:

app.use(jwt({ secret: 'shhhhhhared-secret'}).unless({path: ['/token']}));

Why not having the ability to do something like this:

app.use(jwt({ secret: 'shhhhhhared-secret'}, 
    function(req, res, next){
        // Access req.user and implement more fine-grained authorization
    }
).unless({path: ['/token']}));

or

app.use(jwt({ secret: 'shhhhhhared-secret'})
    .unless({path: ['/token']}))
    .after(function(req, res, next){
        // Access req.user and implement more fine-grained authorization
    }));

Thanks,
Great job!

Stevie

Improve skip functionality

I have an endpoint like this: /api/v1/auth/confirm-email/:secretId and I have the token middleware set on the /api prefix. I would like to be able to set my skip to this: ['/api/v1/auth/confirm-email/*'] or something like that. How do you think this would be best implemented?

checking expiration

Hi,

express-jwt protected path returns 401 when access with invalid token or an expired one, is there a way to know the 401 was returned due to an expired token so that the app can simply log out the user? Thanks,
A.C.

Authorization using query?

Is there anyway you can verify the JWT when its received in the request query? Because currently i am using image urls and can't pass the token in the headers?

Do exists a JAVA implementation project of jwt ?

Hello,

sorry, I don't know how to contact you in another way than creating an issue, I have a question :

Do exists a project proposing a JAVA implementation of jwt ?

Thank you in advance for your response.

Best way to check user scopes

How can I check to make sure if user's jwt token contains certain scopes?

For example, if the user's JWT contains

{ iss: 'http://myapp.iu.edu/auth',
  exp: 1451426441.837,
  iat: 1435874441.837,
  scopes: { common: [ 'do123', 'do456', 'do789' ] },
  sub: '5595b489131dad691a58703d' }

Then, on the server side, I want to make sure that user is authorized for certain tokens by doing something like

router.get('/profile', jwt({secret: publicKey, scopes: {common: 'do123'}}), function(req, res, next) {
    //do 123
});

The README says express-jwt checks for audience, and issuer, but doesn't say anything about scope (and above code doesn't work.. it let user access without any scopes). Is there anyway express-jwt can check for scopes? Or if it's not express-jwt's responsibility, is there a module that does?

Can't customize "UnauthorizedError" response

According to this comment by @jfromaniello the "UnauthorizedError" could be customized by adding the following middleware:

app.use(function (err, req, res, next) {
  if (err.name === 'UnauthorizedError') { 
    res.send(401, 'invalid token...');
  }
});

Unfortunately the error handler above isn't triggered and therefore the response can't be customized.

Version 0.3.2 of express-jwt and version 4.9.0 of Express.js were used for testing this.

Not properly checking expiration time

Express-JWT seems to not properly check the expiration time. Although the token is already expired and I checked it manually in the console, I still have access to the restricted endpoints.

Generating a token:

app.get('/authTest', function (req, res){
    genUuid = uuid.v4();
    token = jwt.sign({uuid: genUuid}, privateKey, {algorithm: 'RS256', expiresInMinutes: 5});
    res.json({token:token});
});

Router middleware to check the token:

router.use(expressJwt({secret: publicKey}));

Check against multiple issuers.

Hi Team!

Thanks for the middleware!

Can we build in the option to have checks against multiple issuers? It may look something like this:

jwt({ secret: 'shhhhhhared-secret',
  audience: 'http://myapi/protected',
  issuer: ['http://issuer1', 'http://issuer2'] })

I looked into express-jwt's index.js and noticed that it all boils down to the use of jwt.verify() from jsonwebtoken.

Someone actually asked how to do this in the JWT-issues. Ultimately, the suggestion is to decode, then check against options:

var expected_issuers = ['issuer1', 'issuer2'];
var decoded = jwt.verify(token, 'secret');
if (expected_issuers.indexOf(decoded.iss) === -1) {
  console.log('unexpected issuer for token');
}

Is this something that we could support? I'd be happy to contribute.

Adam

Misleading revoke section in the README

In the revoke section says:

For example, if the (iss, jti) claim pair is used to identify a JWT:

In auth0/node-jsonwebtoken#36 it says:

...tokens return by Auth0 currently (we are thinking abut adding it in the future) don't return a jti...

Also, in the code sample this are lines are shown but they don't seem to point to any code/library that supports them.

var data = require('./data');
...
data.getRevokedToken(issuer, tokenId, function(err, token){

So, revoke functionality needs to be implemented pretty much from scratch, right?

TypeError: Cannot read property 'split' of undefined

When authenticated before jwt with basic http auth on another url which is not jwt authenticated browser remembers Authorization header, what is malformed for jwt.
This way the parsed jwt token becomes undefined. Maybe setting it to an empty string by default can help.

Where jwt tokens are stored?

Hello, sorry is it possible to know where JWT is actually storing the user token?

When a old token expires it gets automatically deleted (from where its stored) right?

THanks and sorry cause i'm lazy , for sure, but i tryed finding out where tokens are stored without any results :(

Fallback to request headers when custom getToken cannot extract token

Hello, I'd like to be able to pass the token in the querystring but also try the headers if the first doesn't succeed. Currently you would have to rewrite the entire code which extracts the token from the headers, what about making this the default behavior, say, if the custom getToken function returns a falsy value?

Unless bug

Hey,

This unless works on macOs .unless({path: [/\/users\/\w*\/email/i]}), but doesn't on Heroku. (used to let /users/:userid/email)

Is there anything I'm missing?

Thanks,
Philmod

Unnecessary and confusing UnauthorizedError output to console

I have express app with a simple express-jwt implementation. Everything functions fine, however the console shows UnauthorizedError: No Authorization header was found when accessing url paths that are in the .unless(path[..]) array. The response is 200 OK which is what I want, however I think it's really misleading to show UnauthorizedError on the console. Can we please update express-jwt to suppress this message if the path is defined in unless.

I can get around this by creating my own error handler (see below), but I believe I shouldn't have to do this

app.use(function (err, req, res, next) {
    if (err.name === 'UnauthorizedError') {
        res.send(401, 'invalid token...');
    }
});

Using unless path with HTTP Methods

How does one go about using the .unless function passing a path array while also specifying http methods?

I want restrict POST requests to certain routes but not GET requests.

x-access-token for the JWT token

I use Authorization HTTP header for basic authentication mainly. Wouldn't be better to use x-access-token HTTP header to share JWT token?

Even if possible to do:

app.use(jwt({
  secret: ’shhhhht',
  getToken: function(req) {
    if (req.headers && req.headers['x-access-token']) {
      return req.headers['x-access-token'];
    }
    return null;
  }
}));

Compatibility with Sails

I love this repository and I'm trying to use it in a Sails project.

Express middleware in sails as known as policies and internally sails use express 3.x.

Simply you can define a policies and decide what route request pass for each policies (if is necessary).

The interface for create the policy is the same to create a middleware:

module.exports = function(req, res, next) {
 // do something
};

I want to validate the header token with express-jwt and later do a custom action in the policy (for example, search the user and expose in req.user) I'm not sure how to concatenate the middlewares to get in the more external middleware the callback of the express-jwt.

Just something like this:

var options = {secret: 'seeeecret!'};
var expressjwt = require('express-jwt')({options});

module.exports = function(req, res, next) {
  expressjwt(req, res, function(token){
    // Now I have the token
    // do something
    next();
  });
};

Do you think that is possible?

exclusion route

Hi,
got this :app.use('/api', expressJwt({secret: '123'}).unless({path:['/get_price']}));
api is protected, but api/get_price allows un protected access, I did a test, but still get 401:

curl -i -k https://localhost:3000/api/get_price/01
HTTP/1.1 401 Unauthorized
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 77
ETag: W/"4d-118870433"
Date: Sun, 31 Aug 2014 11:15:49 GMT
Connection: keep-alive

<h1>No Authorization header was found</h1>
<h2>401</h2>
<pre>undefined</pre>

why?

"undefined is not a function" on jwt.sign

Code:

jwt = require('express-jwt'),
var token = jwt.sign( { id: user._id }, secret.secretToken, { expireInMinutes: tokenManager.TOKEN_EXPIRATION } )

Error:

        var token = jwt.sign( { id: user._id }, secret.secretToken, { expireInMinut
                        ^
TypeError: undefined is not a function

credentialsRequired is required for the middleware to work

I'm not sure if this is intentional or not, but with the merge of pull request 68189c1 you have to specify the option credentialsRequired: true for the middleware to work, otherwise it will skip validation of the jwt.

If this is expected behaviour if would be good if the readme was updated since it took me a while before I figured out why the middleware wasn't throwing an error as I expected.

Routes not being restricted

Requests made with no token are still being getting a 200 response. What gives?

app.use(expressJwt({
    secret: secret,
    getToken: function fromHeaderOrQuerystring (req) {
        if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
            return req.headers.authorization.split(' ')[1   ];
        } else if (req.query && req.query.token) {
            return req.query.token;
        }
        return null;
    }
}).unless({path: ['/authentication']}));

app.get('/route/protected', function(req, res) {
    res.json({ route: 'should be restricted if no tokens found'});
});

Access token without the Authorization header (cookie?)

I'm in a situation where I need to access req.user without the authorization header being set.
Let's say a user directly go to this path: /test (for example after a callback)
I need to be able to authenticate the user in the route:

app.route('/test')
  .get(function (req, res) {
    // No authorization header, no req.user :(
  });

What I'm doing at the moment is manually set the header by reading the token from a cookie like this:

function setHeader(req, res, next) {
  if(req.cookies && req.cookies.hasOwnProperty('token')) {
    // Copy the token without the quotes
    req.headers.authorization = 'Bearer ' + req.cookies.token.slice(1, req.cookies.token.length -1);
  }
  next();
}

Is there a better solution or am I doing something wrong?

exclusion routes should allow verb to be specified

right now, the jwt middleware will skip all routes in the array passed to jwt().unless(). As far as I can tell, that's irrespective of verb. But there are many cases where you want to secure all routes except for some of the GET routes. For example, you might want to allow anonymous users to read a given document (e.g. GET /articles/:id) but you would not want them to edit or delete that same article (PUT /articles/:id).

Recommend either taking an object into .unless() like so:

jwt({secret: 'keyboard cat'}).unless({ get: ['/articles', '/articles/:id']});

or else parsing the string version from your array, eg:

jwt({secret: 'keyboard cat'}).unless(['GET /articles', 'GET /articles/:id']);

Usage with Passport?

I want to use Passport for it's social strategies, and I want to use express-jwt for email/password JWT authentication, but I have not been able to find any examples of integrating the two. Is there a way to integrate the two? Or is it completely absurd to use them both?

Set the decoded JSON object to req.payload

As the decoded object is the entire payload, would it make sense to assign this to req.payload and let the app finds the user itself and then assigns it to req.user?
I know we can also do jwt({ secret: 'shhhhh', requestProperty: 'payload' });.

No wildcard unless?

I can't seem to do app.use('/api', expressJwt({secret: secret}).unless({path: ['/api/public/*']}));

It seems like I should be able to, but it is not working. I have to specify each individual public route.

Unless `path` should be improved

When subapp is being used like so:

// main.js
var main = express();
var api = require('./api');
main.use('/v1', api);

// api.js
var api = express();
api.use(jwt({...}).unless({path:['/auth/login']});

module.exports = api;

It won't work as long as you prefix auth/login with v1 which makes the whole idea of subapping a bit pointless. As long as it is a middleware, it should be able to take profit from mountpath to prepend the routes, shouldn't it?

Make express-unless optional

Seems very much out of scope to me. While it's nice to show how you can achieve this, it shouldn't be a dependency of express-jwt. Developers can install express-unless separately if they want it. For everyone else, it's just unnecessary additional files.

Maybe worth consideration to remove it for v3?

req.user is out of date

req.user set with user that taken from the jwt that is out of date when user get updated in the db,
this should be fixed

Server sends a 401 response without a WWW-Authenticate header field

The server sends a 401 response without a WWW-Authenticate header field. This does not appear to be compliant with http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2:

The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource

This makes things challenging for Android volley users:
https://stackoverflow.com/questions/17121213/java-io-ioexception-no-authentication-challenges-found

Changelog

It'd be nice to track api changes.

I should add that the semver now states:

Major version zero (0.y.z) is for initial development. Anything may change at any time. The public API should not be considered stable.

So you should get to 1.0.0 to be compliant ;).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.