npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-simple-jwt-auth

v0.1.7

Published

Incorporates endpoint security, middleware that exposes JWT contents as req.user and an /auth route to validate the component

Downloads

16

Readme

express-simple-jwt-auth

WORK IN PROGRESS, NOT FULLY TESTED, DO NOT USE.



Automates validation and decoding of JWT tokens, incorporation of the decoded JWT into req.user as an object, and the addition of role based security in an opinionated database, and an /auth route to validate the JWT and decode it for the client, and a role based security method for end points.

The authenticator is intended to be used with the jwt-simple-login component.


New Notes

Uses password-validator so configuration for that works for passwords

Ensure your custom methods return the not a mongoose object but a json object... use .toJSON() on the result you return.

Authentication requires objects which contain:

{
  ...
  email: '...',
  salt: '...',
  password: '...'
}

Login and create endpoint requires fields: username and password along with any other fields.

Create returns { body, saltHash: { salt: '...', hash: '...' } }

Login returns { body }


Installation

npm i -S jwt-simple-auth

Requirements

Your Mongo database model must include the following:

{
	"email": String,     // For matching with what's in the '.mail' within the jwt.
	"roles": [ String ], // Array of strings of Role names
	"locations": [       // Array of location objects user is associated with (below)
	  { 
	    "city": String,
	    "state": String
	  }
	] // 
}

Usage

Within the app.js file on your node application, require in the component. Somewhere you must define the jwtSecret to validate your Authorization token. Do not store this in your source code as in the example below Use docker-secreto or some other secret management method.

NOTE: If you are using app.use(cors()) you will need to include the route after you add the cors module in.

This module uses express-jwt to manage unless operations

app.js

const { authenticator, authRoute } = require('sso-api-authenticator')

...
const jwtSecret = 'my-secret-password', // Do NOT do this!
      mongoOptions = {
        uri: 'mongodb://someserver.com:27017/db',
        options: {
          ...
        }
      },
      expressJwtOptions = {}
...
// AFTER database connection and mongoose model are defined...

app.use(authenticator(jwtSecret, mongoOptions, expressJwtOptions, {
  path: [
    '/users',
    '/login',
    /\/login\/.*/
  ]
}))

app.use('/auth', authRoute)

After including the above code in your server setup you will gain access to a new object, req.user. This contains all data within the JWT, unencoded as well as relevant roles and locations.

Now, securing a route by role is as simple as adding either req.user.allow() or req.user.deny()

route/users.js

...

router.get('/allow', (req, res, next) => {
  req.user.allow(['Developer'], () => {
    return res.send('The user is a Developer')
  })
  .otherwise(() => {
    res.send('The user does not have the Developer role.')
  })
})


router.get('/deny', (req, res, next) => {
  req.user.deny(['Developer'], () => {
    return res.send('The user does not have the Developer role, so is allowed access.')
  })
  .otherwise(() => {
    res.send('The user is a Developer. None Shall Pass!')
  })
})

...

Parameters

middleware(jwtSecret, MongooseModelForPermissions, expressJwtOptions, unlessObject)

|Param|Required|Definition| |:----|:----:|:---| | jwtSecret|Y|The secret to use for validating your JWT token| | mongoOptions |Y|The database connection object: { uri: 'mongodb://server.com:2017, options: { ... } }.| | expressJwtOptions |N|A passthrough to give access to the express-jwt options. Defaults to {}| |unlessObject|N|An object which is placed into the express-jwt.unless() method. This defines which end points not to protect with JWT security ... like /login |

See express-jwt documentation for details on the expressJwtOptions and unless object settings