Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
JSON Web Token Tutorial: Express
// file: index.js
var _ = require("lodash");
var express = require("express");
var bodyParser = require("body-parser");
var jwt = require('jsonwebtoken');
var passport = require("passport");
var passportJWT = require("passport-jwt");
var ExtractJwt = passportJWT.ExtractJwt;
var JwtStrategy = passportJWT.Strategy;
var users = [
{
id: 1,
name: 'jonathanmh',
password: '%2yx4'
},
{
id: 2,
name: 'test',
password: 'test'
}
];
var jwtOptions = {}
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeader();
jwtOptions.secretOrKey = 'tasmanianDevil';
var strategy = new JwtStrategy(jwtOptions, function(jwt_payload, next) {
console.log('payload received', jwt_payload);
// usually this would be a database call:
var user = users[_.findIndex(users, {id: jwt_payload.id})];
if (user) {
next(null, user);
} else {
next(null, false);
}
});
passport.use(strategy);
var app = express();
app.use(passport.initialize());
// parse application/x-www-form-urlencoded
// for easier testing with Postman or plain HTML forms
app.use(bodyParser.urlencoded({
extended: true
}));
// parse application/json
app.use(bodyParser.json())
app.get("/", function(req, res) {
res.json({message: "Express is up!"});
});
app.post("/login", function(req, res) {
if(req.body.name && req.body.password){
var name = req.body.name;
var password = req.body.password;
}
// usually this would be a database call:
var user = users[_.findIndex(users, {name: name})];
if( ! user ){
res.status(401).json({message:"no such user found"});
}
if(user.password === req.body.password) {
// from now on we'll identify the user by the id and the id is the only personalized value that goes into our token
var payload = {id: user.id};
var token = jwt.sign(payload, jwtOptions.secretOrKey);
res.json({message: "ok", token: token});
} else {
res.status(401).json({message:"passwords did not match"});
}
});
app.get("/secret", passport.authenticate('jwt', { session: false }), function(req, res){
res.json({message: "Success! You can not see this without a token"});
});
app.get("/secretDebug",
function(req, res, next){
console.log(req.get('Authorization'));
next();
}, function(req, res){
res.json("debugging");
});
app.listen(3000, function() {
console.log("Express running");
});
{
"name": "jwt-tutorial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.15.2",
"express": "^4.14.0",
"jsonwebtoken": "^7.1.9",
"lodash": "^4.16.4",
"passport": "^0.3.2",
"passport-jwt": "^2.1.0"
}
}
@dumptyd

This comment has been minimized.

Show comment Hide comment
@dumptyd

dumptyd Jan 10, 2017

Thanks 👍

dumptyd commented Jan 10, 2017

Thanks 👍

@developermhayden

This comment has been minimized.

Show comment Hide comment
@developermhayden

developermhayden Mar 21, 2017

Thank you for this sample.
I have a question in regards to this part:

app.get("/secret", passport.authenticate('jwt', { session: false }), function(req, res){
  res.json({message: "Success! You can not see this without a token"});
});

when I do the get request I get:

Unauthorized

Do I set a header parameter passing in the token with that get request?
How do I use the generated token with that GET request to get the success message?

Thank you for this sample.
I have a question in regards to this part:

app.get("/secret", passport.authenticate('jwt', { session: false }), function(req, res){
  res.json({message: "Success! You can not see this without a token"});
});

when I do the get request I get:

Unauthorized

Do I set a header parameter passing in the token with that get request?
How do I use the generated token with that GET request to get the success message?

@nikolay-govorov

This comment has been minimized.

Show comment Hide comment
@nikolay-govorov

nikolay-govorov Apr 25, 2017

Thank, it is that I need! 👍

Thank, it is that I need! 👍

@PJCHENder

This comment has been minimized.

Show comment Hide comment
@PJCHENder

PJCHENder Jun 21, 2017

Great Article!!

Great Article!!

@Evgenyx82

This comment has been minimized.

Show comment Hide comment
@Evgenyx82

Evgenyx82 Aug 18, 2017

developermhayden use fetch polyfill with headers options (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)

developermhayden use fetch polyfill with headers options (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)

@harrylincoln

This comment has been minimized.

Show comment Hide comment
@harrylincoln

harrylincoln Aug 23, 2017

TypeError: ExtractJwt.fromAuthHeader is not a function

Line 28 needs to change to: jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt'); ?

Reference: https://www.npmjs.com/package/passport-jwt#migrating-from-2xx-to-3xx

harrylincoln commented Aug 23, 2017

TypeError: ExtractJwt.fromAuthHeader is not a function

Line 28 needs to change to: jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt'); ?

Reference: https://www.npmjs.com/package/passport-jwt#migrating-from-2xx-to-3xx

@YemSalat

This comment has been minimized.

Show comment Hide comment
@YemSalat

YemSalat Sep 8, 2017

@JonathanMH for some reason I cant get expiration to work w/ your gist
var jwtOptions = { jwtFromRequest: ExtractJwt.fromHeader('auth'), secretOrKey: 'tasmanianDevil', ignoreExpiration: false, jsonWebTokenOptions: { expiresIn: '10s' } }

I still see the success message for every request I make.

[EDIT]
FIXED, by replacing this line: https://gist.github.com/JonathanMH/6bd82c0954fb8f21a837ce281da4265a#file-index-js-L74
with jwt.sign(payload, jwtOptions.secretOrKey, jwtOptions.jsonWebTokenOptions);

YemSalat commented Sep 8, 2017

@JonathanMH for some reason I cant get expiration to work w/ your gist
var jwtOptions = { jwtFromRequest: ExtractJwt.fromHeader('auth'), secretOrKey: 'tasmanianDevil', ignoreExpiration: false, jsonWebTokenOptions: { expiresIn: '10s' } }

I still see the success message for every request I make.

[EDIT]
FIXED, by replacing this line: https://gist.github.com/JonathanMH/6bd82c0954fb8f21a837ce281da4265a#file-index-js-L74
with jwt.sign(payload, jwtOptions.secretOrKey, jwtOptions.jsonWebTokenOptions);

@lmontoya1974

This comment has been minimized.

Show comment Hide comment
@lmontoya1974

lmontoya1974 Sep 8, 2017

Hi,
I have all working now and I'm getting===== > "Success! You can not see this without a token".

I need to continue with my application and adding more options like:

app.post("/read", function(req, res) {  
     **//
    // do all here just when the access is granted, but error if no access or  "Unauthorized"
   //**
	} 

What else I need to include?

Thank you all guys.

Hi,
I have all working now and I'm getting===== > "Success! You can not see this without a token".

I need to continue with my application and adding more options like:

app.post("/read", function(req, res) {  
     **//
    // do all here just when the access is granted, but error if no access or  "Unauthorized"
   //**
	} 

What else I need to include?

Thank you all guys.

@premgowda

This comment has been minimized.

Show comment Hide comment
@premgowda

premgowda Nov 28, 2017

@developermhayden

prefix token with JWT
example : "JWT token"

@developermhayden

prefix token with JWT
example : "JWT token"

@wisetc

This comment has been minimized.

Show comment Hide comment
@wisetc

wisetc Dec 29, 2017

I used ExtractJwt.fromAuthHeaderAsBearerToken() instead of ExtractJwt.fromAuthHeader() and set Authorization header to 'Bearer ' + token.
image

image

It worked.

wisetc commented Dec 29, 2017

I used ExtractJwt.fromAuthHeaderAsBearerToken() instead of ExtractJwt.fromAuthHeader() and set Authorization header to 'Bearer ' + token.
image

image

It worked.

@jjjjcccjjf

This comment has been minimized.

Show comment Hide comment
@jjjjcccjjf

jjjjcccjjf Jan 6, 2018

@wisetc I used this instead
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('bearer');

jjjjcccjjf commented Jan 6, 2018

@wisetc I used this instead
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('bearer');

@soumodips

This comment has been minimized.

Show comment Hide comment
@soumodips

soumodips Feb 3, 2018

Hello everyone. I still have this issue. Tried using bearer strategy too. Here is the link to my repo https://github.com/soumodips/JWT-passport-OAuth

I will be glad if any one can help.

Screenshots from Postman:
image

image

Thanks a ton in advance!

ISSUE SOLVED:
Be sure to use all key names as expected by the modules. I had used 'exp' for expiry time in the payload instead of 'expiresIn'. Enjoy!!

soumodips commented Feb 3, 2018

Hello everyone. I still have this issue. Tried using bearer strategy too. Here is the link to my repo https://github.com/soumodips/JWT-passport-OAuth

I will be glad if any one can help.

Screenshots from Postman:
image

image

Thanks a ton in advance!

ISSUE SOLVED:
Be sure to use all key names as expected by the modules. I had used 'exp' for expiry time in the payload instead of 'expiresIn'. Enjoy!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment