express-jwtk

JSON Web Token Authentication support for Express.

Usage no npm install needed!

<script type="module">
  import expressJwtk from 'https://cdn.skypack.dev/express-jwtk';
</script>

README

express-jwtk

Build Status

JSON Web Token Authentication support for Express.

New to using JSON Web Token? Take a look at these resources:

Installation

npm install -S express-jwtk

Usage

const jwtAuth = require('express-jwtk')(options);

options:

  • secret: String, the secret which is used in signing header and payload
  • requestProperty (optional): String, the name of property which is used in visiting infomation in JSON Web Token, default value is 'user'

Example:

'use strict';

const express = require('express');
const jwtAuth = require('express-jwtk')({secret: 'secret'});
const app = express();

app.get('/jwtAuth-protected', jwtAuth, (req, res) => {
  res.json({
    msg: 'I am protected by jwt auth',
  });
});

app.listen(3000);

Now, the route is protected by JSON Web Token, and requires an authorization header in the request:

Authorization: Bearer <token>

Then, visit the infomation in JSON Web Token via req.user.

Error Handling

When authorization fails, express-jwtk will throw an instance of UnauthorizedError. You can add custom logic to manage unauthorized access as follows:

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

LICENSE

MIT