다음의 모듈을 설치한다. yarn으로 안되면 npm으로 깐다.

npm install --save jsonwebtoken

파이썬 jwt와 그 구성은 같은데 단지 함수 명이 다를 뿐이다.

다음과 같이 jwt로 encode가 가능하다.

const token = jwt.sign(제이슨, "비밀키"); 
/*비밀키 뒤에 , 를 붙이고 알고리즘을 무엇을 쓸지 넣을 수 있는데
 안쓰면 기본값으로 HS256 알고리즘이 적용된다.*/

다음과 같은 jwt로 decode가 가능하다.

const token = req.headers.authorization; // headers로 header에 담긴 토큰을 빼온다.
const decoded = jwt.verify(token, "비밀키");
/*빼온 토큰을 넣고 비밀키를 넣어 토큰을 검증한다.*/

예제

import express from "express";
import bodyParser from "body-parser";
import jwt from "jsonwebtoken";

const app = express();

const handlerServer = () => {
  console.log("<http://localhost:4000> ON");
};

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post("/", (req, res) => {
  try {
    const body = req.body;
    const tokenExp = { exp: Math.floor(Date.now() / 1000) + 60 * 60 };
		// exp는 토큰의 생명시간을 설정하는 것으로 해당 시간이 지나면 토큰을 재발급 받아야 한다.
    const data = Object.assign({}, body, tokenExp);
    const token = jwt.sign(data, "wecode");
    res.status(200).send(token);
  } catch (e) {
    console.log(e);
    throw e.Error;
  }
});

app.get("/test", (req, res) => {
  try {
    console.log(req.headers);
    const token = req.headers.authorization;
    console.log(token);
    const decoded = jwt.verify(token, "wecode");
    console.log(decoded);
    res.status(200).json(decoded);
  } catch (e) {
    console.log(e);
    throw e.Error;
  }
});

app.listen(4000, handlerServer);