salep salep - 7 months ago 51
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 : , 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.

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');


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.get('/', function (req, res) {

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);


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); //`` 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)