question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

API route permissions using an express-jwt-permissions guard on node.js

See original GitHub issue

Originally posted on Stack Overflow

I am attempting to use express-jwt-permissions to protect an API route and I am unable to use the guard syntax “guard.check(‘user’)”. I have successfully used express-jwt which express-jwt-permissions builds upon.

An interesting fact is that express-jwt requires the JWT_SECRET to be assigned to it, whereas there are no instruction on the express-jwt-permissions docs to understand this interplay or perhaps there is some example missing?

My current code is as follows:

/////////////////////////////////////////////
// auth.ts - Auth and set user permissions
/////////////////////////////////////////////
router.post('/', async (request, response, next) => {
    const {email, password} = request.body

    try {
        // Authenticate
        const user = await authenticate(email, password)
        user.permissions = ['user'] // set the express-jwt-permissions here

        // Create JWT token
        let token = jwt.sign(user.toJSON(), process.env.JWT_SECRET, {
            expiresIn: '60m'
        })

        let {iat, exp} = jwtDecode(token)

        // Respond with token
        response.status(HttpStatus.OK).send({iat, exp, token})
    

...

I successfully retrieved a JWT token from the ‘api/auth’ endpoint.

{
    "iat": 1559650778,
    "exp": 1559654378,
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwZXJtaXNzaW9ucyI6WyJ1c2VyIl0sIl9pZCI6IjVjZjUyZjc1NDA4MTk0YWI1MGZlMWNkNiIsIm5hbWUiOiJHYXJ5IFBhbHVrIiwiZW1haWwiOiJnYXJ5QHBsdWdpbi5pbyIsInVzZXJuYW1lIjoiZ2FyeSIsInBhc3N3b3JkIjoiJDJhJDEwJEt1U1NUQXowd1MxNU5tRjRVQjZQb2VMTC5Ya1phZkc5Sm9xVkVRWnZZcHFkTFNrZXliTU1lIiwidXBkYXRlZEF0IjoiMjAxOS0wNi0wM1QxNDozMjoyMS4zMDlaIiwiY3JlYXRlZEF0IjoiMjAxOS0wNi0wM1QxNDozMjoyMS4zMDlaIiwiX192IjowLCJpYXQiOjE1NTk2NTA3NzgsImV4cCI6MTU1OTY1NDM3OH0.qnfH_OHq2YqaKCRIbwtw788SQC51F8PJESRCf3Nlrak"
}

I then attempted to authorize with combinations of Bearer Token, OAuth2, prepending token with/without 'jwt ’ etc, but nothing seems to get past the route guard on ‘api/registry’.

/////////////////////////////////////////////
// server.ts - API auth routes
/////////////////////////////////////////////
server.use(
    '/api/registry',
    guard.check('user'),
    require('./api/v1/registry')
)

server.use('/api/auth', require('./api/v1/auth'))


...

Result:

{
    "name": "UnauthorizedError",
    "message": "user object \"user\" was not found. Check your configuration.",
    "code": "user_object_not_found",
    "status": 403,
    "inner": {
        "message": "user object \"user\" was not found. Check your configuration."
    }
}

The expected result would be that I can make an API call to ‘/api/registry’ with the JWT token as a bearer token / OAuth2? and that should let me pass the route guard.

Thanks

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:13 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
MichielDeMeycommented, Jun 4, 2019

Can you show me the complete setup of the middleware? express-jwt must be configured before express-jwt-permissions.

e.g.

app.use(jwt({secret: process.env.JWT_SECRET}))

app.get('/protected', guard.check('user'), (req, res) => {})
1reaction
MichielDeMeycommented, Jun 4, 2019

Yes, but how is express-jwt currently configured? To configure it, check https://github.com/auth0/express-jwt

Example from their documentation:

jwt({ secret: 'shhhhhhared-secret',
  audience: 'http://myapi/protected',
  issuer: 'http://issuer' })
Read more comments on GitHub >

github_iconTop Results From Across the Web

API route permissions using an express-jwt ... - Stack Overflow
I am attempting to use express-jwt-permissions to protect an API route and I am unable to use the guard syntax "guard.check('user')".
Read more >
express-jwt-permissions - npm
Using permission Array​​ If you require different permissions per route, you can set the middleware per route. var guard = require('express-jwt- ...
Read more >
Securing your node.js Express application with OneGraph ...
AuthGuardian has excellent support for express-jwt-permissions . For any rule, simply Add to list at path (with path set to permissions ). Consider...
Read more >
Node.js and TypeScript Tutorial: Secure an Express API - Auth0
Learn how to use TypeScript and Auth0 to secure a feature-complete Express.js API. Learn how to use Auth0 to implement authorization in Express....
Read more >
Node.js - Role Based Authorization Tutorial with Example API
The authorize middleware can be added to any route to restrict access to authenticated users within specified roles. If the roles parameter is ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found