在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接口的一种有效方式。这种方法不仅使代码更加简洁明了,还能确保系统的安全性和稳定性。

相关推荐
java66666888810 分钟前
深入理解Spring Boot中的容器与依赖注入
java·spring boot·后端
u01040583617 分钟前
Spring Boot中的依赖注入和控制反转
java·spring boot·后端
Qiuner24 分钟前
两年经验前端带你重学前端框架必会的ajax+node.js+webpack+git等技术 Day2
ajax·前端框架·node.js
虫小宝1 小时前
解决Spring Boot中的安全漏洞与防护策略
java·spring boot·后端
test6381 小时前
使用ThreadLocal存储用户登录信息
java·后端·面试
续亮~2 小时前
6、Redis系统-数据结构-06-跳表
java·数据结构·数据库·redis·后端·缓存
五敷有你3 小时前
Go:hello world
开发语言·后端·golang
拔剑纵狂歌3 小时前
Golang异常处理机制
开发语言·后端·golang·go
缘友一世3 小时前
Armbian 1panel面板工具箱中FTP服务无法正常启动的解决方法
linux·运维·后端·1panel
weixin_419349793 小时前
flask使用定时任务flask_apscheduler(APScheduler)
后端·python·flask