在Egg.js中使用中间件实现用户登录验证

在Egg.js中使用中间件实现用户登录验证

在本篇博客中,我们将探讨如何在Egg.js框架中通过中间件实现token验证,以确保用户的合法身份。这一技术在需要安全访问的API接口中尤为重要。

1. 在 service/user.js 中添加验证token函数

首先,我们在 service/user.js 文件中创建一个函数来验证token。这个函数使用了 jsonwebtoken 库来解析和验证token。

js 复制代码
const Service = require('egg').Service
const jwt = require('jsonwebtoken')

class UserService extends Service {
  verifyToken(token) {
    return jwt.verify(token, this.app.config.jwt.secret)
  }
}

2. 新建 middleware/auth.js

接下来,我们在 middleware 目录下新建一个 auth.js 文件。这个中间件将负责提取请求头中的token,并调用之前创建的验证函数进行验证。

js 复制代码
module.exports = (options = { required: true }) => {
  return async (ctx, next) => {
    let token = ctx.headers.authorization
    token = token ? token.split('Bearer ')[1] : null
    if (token) {
      try {
        const data = ctx.service.user.verifyToken(token)
        ctx.user = data.user
      } catch (error) {
        ctx.throw(401, 'token验证失败')
      }
    } else if (!options.required) {
      await next()
    } else {
      ctx.throw(401, 'token未传入')
    }
    await next()
  }
}

3. 新建路由进行验证

最后,我们在路由文件中配置路由,使其在访问某些特定接口时,先通过token验证中间件。

js 复制代码
module.exports = app => {
  const { router, controller } = app;
  // 添加前缀
  router.prefix('/api/v1')
  // 用户频道
  router.post('/users/info', app.middleware.auth(), controller.user.userInfo)
};

总结

通过以上步骤,我们成功地在Egg.js项目中实现了一个基于中间件的token验证机制。此实现方法确保了只有携带有效token的请求才能访问特定的API接口,从而提高了系统的安全性。

总之,使用中间件进行token验证是保护API接口的一种有效方式。这种方法不仅使代码更加简洁明了,还能确保系统的安全性和稳定性。

相关推荐
moxiaoran57534 分钟前
Go语言的错误处理
开发语言·后端·golang
短剑重铸之日6 小时前
《7天学会Redis》特别篇: Redis分布式锁
java·redis·分布式·后端·缓存·redission·看门狗机制
小北方城市网6 小时前
SpringBoot 全局异常处理与接口规范实战:打造健壮可维护接口
java·spring boot·redis·后端·python·spring·缓存
hanqunfeng7 小时前
(三十三)Redisson 实战
java·spring boot·后端
小北方城市网7 小时前
SpringBoot 集成 MyBatis-Plus 实战(高效 CRUD 与复杂查询):简化数据库操作
java·数据库·人工智能·spring boot·后端·安全·mybatis
hanqunfeng9 小时前
(四十)SpringBoot 集成 Redis
spring boot·redis·后端
小北方城市网9 小时前
SpringBoot 集成 MinIO 实战(对象存储):实现高效文件管理
java·spring boot·redis·分布式·后端·python·缓存
程序员泠零澪回家种桔子9 小时前
RAG自查询:让AI精准检索的秘密武器
人工智能·后端·算法
曹轲恒10 小时前
SpringBoot配置文件(1)
java·spring boot·后端
嘿嘻哈呀10 小时前
Node.js和包管理工具
node.js