salep salep - 1 year ago 320
Node.js Question

NodeJS JWT token verification

I'm trying to verify a signed token and extract information from it using NodeJS.

I have a token named userToken in the browser right now, it has been saved after I logged in (I use auth0 to login by the way).

I tried to verify my token here manually : http://jwt.io , it works and gives me payload data without a problem. However, I can't do the same thing with NodeJS. How can I do it?

I read the docs but I couldn't get it.
https://github.com/auth0/express-jwt

Here's my server.js

var http = require('http');
var express = require('express');
var cors = require('cors');
var app = express();
var jwt = require('express-jwt');
var dotenv = require('dotenv');

dotenv.load();

var authenticate = jwt({
secret: new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64'),
audience: process.env.AUTH0_CLIENT_ID
});


// view engine setup
var path = require('path');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));

app.set('view engine', 'jade');


app.configure(function () {

// Request body parsing middleware should be above methodOverride
app.use(express.bodyParser());
app.use(express.urlencoded());
app.use(express.json());
app.use(cors());

app.use(app.router);
});


app.get('/', function (req, res) {
res.render('index');
});

app.get('/test', function(req,res) {
// how do I check it?
});


var port = process.env.PORT || 3001;

http.createServer(app).listen(port, function (err) {
console.log('listening in http://localhost:' + port);
});

Answer Source

This sample should help you, it's not tested, but sure it's right way, look at source of express-jwt, it does literally same behind the scenes

app.get('/test', function(req, res) {
    var jsonwebtoken = require('jsonwebtoken'); //install this, move to declarations
    var loginToken = req.headers.authentication || req.body.userToken || req.headers.Bearer; //or your own, it's just headers that pass from browser to client
    jsonwebtoken.verify(loginToken, new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64'), function(err, decoded) {
        if(err) {
            return res.status(401).send({message: 'invalid_token'});
        }
        //be aware of encoded data structure, simply console.log(decoded); to see what it contains
        res.send(decoded); //`decoded.foo` has your value
    });
});

The thing is that you must yourself encode your data, and then decode, so be aware that auth0 returns valid data structure for you (as i'm not sure otherwise)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download