0

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' }); 
4
  • Your express-jwt logic works for me. Are you sending a valid JWT within the Authorization header in Postman? Commented Feb 1, 2017 at 11:09
  • @dan I want to check the unautorizedError and catched that in app.js something like app.use(function (err, req, res, next) { if (err.name === 'UnauthorizedErorr') { res.status(401); res.json("message : " + err.name + " : " + err.message); } }); and expect a message response. Commented Feb 1, 2017 at 11:13
  • @dan Sorry, checked again i have a type mistake in app.js (UnauthorizedErorr ). Thank u Commented Feb 1, 2017 at 11:15
  • Ok, I've posted an answer to show an example of that. Hopefully that helps. Commented Feb 1, 2017 at 11:52

1 Answer 1

2

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') }) 
Sign up to request clarification or add additional context in comments.

1 Comment

To me the secret, the jump of the cat, was the key requestProperty, I updated the package express-jwt and the key has changed from userProperty to new requestProperty.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.