• base::

    jwt

    前端

    适用范围:

    1. 特点:

    • 服务器保存的信息就少了
      • 只需要保存解密的密钥
    • 将信息保存在jwt中, 并交给客户端保存

    防御

    • token安全防御
      • 如果需要放在请求头中,则用户可以抓包获取
      • 所以需要设置有效期,定时刷新

    梗概:

    • Json Web Token是一种前后端通用的技术
    • 将登陆信息(用户名和密码)经过服务器的密钥加密, 然后保存在token中, 并把token交给客户端保存
    • 用户向服务器发出http请求的时候, 可以带上保存好的token
    • 服务器接受token后, 解密token, 得到验证信息
    指向原始笔记的链接

梗概

  • 使用第三方库来生成和检验token

示例

const Koa = require('koa');
const Router = require('koa-router');
const jwt = require('jsonwebtoken');
 
const app = new Koa();
const router = new Router();
 
// Replace with your own secret key
const secretKey = 'secretKey';
 
// Middleware to verify JWT token
const verifyToken = async (ctx, next) => {
  const token = ctx.headers.authorization;
 
  if (!token) {
    ctx.status = 401;
    ctx.body = { message: 'Unauthorized' };
    return;
  }
 
  try {
    const decoded = jwt.verify(token, secretKey);
    ctx.state.user = decoded;
    await next();
  } catch (error) {
    ctx.status = 401;
    ctx.body = { message: 'Invalid token' };
  }
};
 
// Generate JWT token
router.get('/login', async (ctx) => {
  //假设这是从用户接收到的登陆信息
  const user = { id: 1, username: 'john.doe' };
  
  const token = jwt.sign(user, secretKey);
  
  ctx.body = { token };
});
 
// Protected route that requires valid JWT token
router.get('/protected', verifyToken, async (ctx) => {
  ctx.body= { message: 'Protected route accessed successfully' };
});
 
app.use(router.routes());
app.use(router.allowedMethods());
 
app.listen(3000, () => {
	console.log('Server running on port 3000');
});

This example demonstrates how to implement JWT authentication using Koa. The verifyToken middleware is used to check the validity of the JWT token sent in the request header. The /login endpoint generates a new JWT token for a user and the /protected endpoint is protected and requires a valid JWT token to access.