JWT

JSON Web Token (JWT) is a JSON based scheme to securely transfer information between two parties. To make a request that uses JWT, generate the token and use it in the request. To enable JWT authorization, you can use the jsonwebtoken and request npm packages. Specify the package names and version numbers as dependencies in the manifest.json file and include the code corresponding to the packages in the server.js file.

manifest.json

Copied Copy
1
2
3
4
"dependencies": { "jsonwebtoken": "8.1.1", "request": "2.72.0" }

The JWT is generated from data comprising of three parts - header, payload, and signature. The data is signed by the secret or private key. The generated token is passed in the Authorization header of a request.

server.js

Copied Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var jwt = require('jsonwebtoken'); var request = require('request'); function jwt_request(){ // { foo: 'bar' } is the data and secret is the secret or private key var jwt_token = jwt.sign({ foo: 'bar' }, 'secret', { expiresIn: '1h' }); var options = { url: 'https://url.com', method: "POST", headers: { 'Authorization': jwt_token } }; request(options, function(error, response, body){ //logic to handle success or failure }); }
EXPAND ↓