jones
jones

Reputation: 1453

express-jwt authentication middleware not working

I'm using express-jwt for athentication, and the following is my code:

api>routes/index.js:

var express = require('express');
var router  = express.Router();

var jwt = require('express-jwt');
var auth = jwt({ secret: 'thisIsSecret', requestProperty: 'auth' });

after this inside index.js when i use auth middleware in

router.post('/locations/:locationId/reviews', auth, ctrlReviews.reviewsCreate);

route, when want to post reviews data with post-man, request goes to loading, and no response appear, but if remove auth from route request give response. I have also checked with

var auth = jwt({
  secret: process.env.JWT_SECRET,
  userProperty: 'payload'
});

Upvotes: 0

Views: 3148

Answers (1)

dan
dan

Reputation: 1984

As mentioned in the comments, you're trying to handle valid and invalid tokens. This should be possible with something similar to the below code.

If you use Postman to call this with the following header, then you'll receive 200 OK, with a message of 'OK!'.

Authorization: Bearer validJWT

If you use Postman to call this without a valid JWT then you'll receive 401 Unauthorized with a message of 'invalid token...'.

var jsonwebtoken = require('jsonwebtoken');
var express = require('express');
var app  = express();

var jwt = require('express-jwt');
var auth = jwt({ secret: 'thisIsSecret', requestProperty: 'auth'});

// Generate valid JWT
console.log(jsonwebtoken.sign({ foo: 'bar' }, 'thisIsSecret'));

app.post('/locations/:locationId/reviews', auth, function(req, res, next) {
    // Log user details set in JWT
    console.log(req.auth)
    res.send('OK!');
});

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

app.listen(3000, function() {
    console.log('Server running on 3000')
})

Upvotes: 2

Related Questions