egg-jwt

1.0 jwt思路

  1. 用户输入用户名和密码登陆,若是用户名和密码正确的话,使用 jsonwebtoken.sign() 生成 token,并返回给客户端。
  2. 客户端将token存储在本地存储,在每次的 HTTP 请求中,都将 token 添加在 HTTP Header Authorazition: Bearer token 中。
  3. 而后后端每次去验证该token的正确与否。只有token正确后才能访问到对应的资源。

githubgit

1.1 安装依赖

cnpm install jsonwebtoken --save
复制代码

1.2 配置jwt的secret(密钥)

config\config.default.jsgithub

config.jwt = {
    secret: '我是密钥',
  };
复制代码

1.3 用户登陆,根据userId存储jwt

app\controller\home.jsweb

async jwt() {
    const { ctx } = this;
    const userId = '123456';
    const result = await ctx.service.jwt.signJwt(userId);
    const data = await ctx.service.jwt.verifyJwt(result);
    ctx.body = data;
  }
复制代码

1.4 sign签名

  1. 第一个参数,要加密的数据
  2. 第二个参数,加密的密钥
  3. 第三个参数,对象,过时时间
async signJwt(userId) {
    const { ctx } = this;
    const token = jwt.sign({ userId }, this.config.jwt.secret, {
      expiresIn: 60,
    });
    return token;
  }
复制代码

1.5 verify检验`

async verifyJwt(token) {
    const { ctx } = this;
    try {
      let hasToken = false;
      const userId = jwt.verify(token, this.config.jwt.secret).userId;
      console.log(userId);
      if (userId == '123456') {
        hasToken = true;
        return hasToken;
      }
      return hasToken;

    } catch (err) {
      throw (err);
    }
  }
复制代码

1.6 效果

本站公众号
   欢迎关注本站公众号,获取更多信息