Skip to content

Instantly share code, notes, and snippets.

@gillesdemey
Last active February 7, 2021 02:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gillesdemey/df4f9189e4338819d8bff450984db2e1 to your computer and use it in GitHub Desktop.
Save gillesdemey/df4f9189e4338819d8bff450984db2e1 to your computer and use it in GitHub Desktop.
express-jwt-permissions with express-unless
const express = require('express')
const jwt = require('express-jwt')
const permissions = require('express-jwt-permissions')()
const unless = require('express-unless')
const app = express()
const checkAuth = jwt({ secret: process.env.JWTSECRET })
const checkAdmin = permissions.check(['admin'])
checkAdmin.unless = unless
// apply permissions check to all routes
app.use(checkAuth, checkAdmin.unless({ path: '/public' }))
// should check for admin permissions
app.get('/private', (req, res) => {
res.send('super secret')
})
// should not check for admin permissions
app.get('/public', (req, res) => {
res.send('not so secret')
})
app.listen(3000)
{
"name": "jwt-permissions-unless",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.14.0",
"express-jwt": "^5.1.0",
"express-jwt-permissions": "^0.5.0",
"express-unless": "^0.3.0"
}
}
@gillesdemey
Copy link
Author

JWTSECRET=foo node index.js
$ curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicGVybWlzc2lvbnMiOltdfQ.BIa3fBp6a9O6HcUPZj28URY8q3T26ZIAAOIWncVpGZ0" http://localhost:3000/private
$ UnauthorizedError: Permission denied
$ curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicGVybWlzc2lvbnMiOltdfQ.BIa3fBp6a9O6HcUPZj28URY8q3T26ZIAAOIWncVpGZ0" http://localhost:3000/public
$ not so secret                                      

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment