I want to implement authentication using JWT in expressJS app.
I have learned JWT concept after googling some web sites but I am not able to implement JWT using expressJS.
I am not getting any exact example for JWT in expressJS.
I have read read-me note of express-jwt node module but my issue is how to generate JWT and how to verify received JWT for each request.
What is exact process to :
var jwt = require('express-jwt'); app.get('/protected', jwt({ secret: 'shhhhhhared-secret' }), function(req, res) { if (!req.user.admin) return res.send(401); res.send(200); });
You'll need to use the package jsonwebtoken. The express-jwt
package is what helps you protect portions of your API when you're using the ExpressJS framework.
The secret is much like a password. It encodes the payload so that sensitive information can be passed around in the JWT without being manipulated. It gives certainty that the authentication mechanism hasn't been altered, and therefore the server can trust that user.
Note: In some cases you'll see JWT's encoded with the RS256 algorithm. This will require that a public/private key pair is provided to verify and decode the JWT.
Generate
The sign()
function does this in jsonwebtoken
. If you use the jwt-simple package you'll use encode()
.
You can sign a JWT with any secret, but you'll have to use that same secret to use verify()
.
Assume you have the following JSON object that you want to make a JWT:
var json = { user: 'jdoe',
firstName: 'John',
lastName: 'Doe',
id: 1
};
var token = jwt.sign(json, 'superSecretSquirrel');
Your signed/encoded token will now look like:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiamRvZSIsImZpcnN0TmFtZSI6IkpvaG4iLCJsYXN0TmFtZSI6IkRvZSIsImlkIjoxLCJpYXQiOjE0MzI3NjU3NzJ9.4mowMfRKIENnAKtRdDkj-BZZqAS8_b0eS3nj5qvEu9Q
You can verify this at jwt.io (make sure you provide the secret given here).
Verify and Decode
The verify()
function does this asynchronously. The object it returns in the callback is a decoded JWT. In order to verify a JWT, you need to pass the secret to the function.
Assuming the secret of 'superSecretSquirrel' as shown above:
var jwt = require('jsonwebtoken');
jwt.verify(token, 'superSecretSquirrel', function (err, decoded) {
if (err)
console.error(err);
// Show the decoded JWT
console.log(decoded);
});
The decoded token will show as:
{ user: 'jdoe', firstName: 'John', lastName: 'Doe', id: 1, iat: 1432765772 }
Where the iat
in the token is a registered claim that means 'Issued At'.
Now let's refer to your example (I left out the function and replaced the secret):
var expressJWT = require('express-jwt');
// Assume app = express();
app.get('/protected',
expressJWT({
secret: 'superSecretSquirrel'
}),
...
);
What this does is only allow access to the path /protected
if you have a JSON Web Token that is signed with the secret 'superSecretSquirrel'. If you have a token with a secret that doesn't match, you'll get a UnauthorizedError
, and you'll want to throw a HTTP 401.