Search code examples
node.jsjwtkoa

How to use jwt in koa2 & nodejs


I have a page written in nodejs and koa, and I'm a little confused about JWT, please check following code.

'use strict';
const Router = require("koa-router");
const router = new Router({prefix: '/login'});
const jwt = require('jsonwebtoken');
const jwtkey = "123456";
router
    .get('/', async (ctx, next) => {
        await ctx.render("login", {
            
        });
    })
    .post('/', async (ctx, next) => {
        try {
            let email = ctx.request.body.email || "";
            let password = ctx.request.body.password || "";
            //check user
            if (islogin) {
                let payload = {
                    email: email,
                    password: sha1(password).toString()
                }
                let token = jwt.sign(payload, jwtkey, {expiresIn: '3h'});
                ctx.body = {"error": false, "msg": token};
            } else {
                throw "Wrong";
            }
        } catch (e) {
            ctx.body = {error:true, msg: e instanceof Error ? e.message : e};
        }
    })
module.exports = router;

I want to implement that when accessing the login page, if the token generated by jwt exists on the server side and is correct, then console.log("logined"),if not, show the login page.

.get('/', async (ctx, next) => {
  //how to verify the token?
  if(token) {
     console.log("logined");
  } else {
    await ctx.render("login", {
            
    });
  }
})

Thank you.


Solution

  • After generating the token you should set that token in user's browser as cookie or some other way,

    Then while requesting / page check for the token and verify the validity

    var decoded = jwt.verify(token, key);