如何在Strapi中为/auth/local登录路由添加专属中间件?
为Strapi内置/auth/local路由单独添加中间件(无需全局配置)
可以实现,无需配置全局中间件,直接针对内置的/auth/local登录路由挂载专属中间件,以下是具体实现方案:
方案一:扩展内置路由并挂载自定义中间件
这种方法直接针对目标路由添加中间件,仅作用于内置登录处理器,精准高效。
步骤1:创建插件扩展文件
在项目根目录创建src/extensions/users-permissions/strapi-server.js(若不存在则新建),用于修改内置users-permissions插件的路由配置:
import { Strapi } from '@strapi/strapi'; export default (strapi: Strapi) => { // 获取内置的内容API路由集合 const authRoutes = strapi.plugin('users-permissions').routes['content-api'].routes; // 定位到/auth/local的POST登录路由 const localLoginRoute = authRoutes.find(route => route.path === '/auth/local' && route.method === 'POST' ); if (localLoginRoute) { // 为该路由添加自定义验证中间件(保留原有中间件) localLoginRoute.config.middlewares = [ ...(localLoginRoute.config.middlewares || []), 'global::custom-login-validation' // 自定义中间件的注册名称 ]; } };
步骤2:编写自定义验证中间件
在src/middlewares/custom-login-validation.js(TypeScript项目用.ts)中编写你的额外验证逻辑:
import { Strapi } from '@strapi/strapi'; export default (config, { strapi }: { strapi: Strapi }) => { return async (ctx, next) => { // 从请求体中获取登录参数 const { identifier, password } = ctx.request.body; // 示例验证逻辑:检查邮箱格式 if (!identifier || !identifier.includes('@')) { return ctx.badRequest('请输入有效的邮箱地址'); } // 示例:检查密码长度 if (!password || password.length < 6) { return ctx.badRequest('密码长度不能少于6位'); } // 验证通过后,继续执行内置登录逻辑 await next(); }; };
步骤3:重启Strapi服务
修改配置后重启服务,自定义中间件会自动挂载到/auth/local的POST请求上,仅对该路由生效。
方案二:优化全局中间件的匹配逻辑(不推荐)
如果你坚持使用全局中间件的方式,可以优化路由匹配逻辑,避免误判:
import { Strapi } from "@strapi/strapi"; export default (config, { strapi }: { strapi: Strapi }) => { return async (ctx, next) => { // 用Strapi内置的路由匹配工具精准判断 const matchedRoute = strapi.router.match(ctx.request.url, ctx.request.method); if (matchedRoute && matchedRoute.route.path === '/auth/local' && matchedRoute.route.method === 'POST') { // 执行你的额外验证逻辑 // ... } await next(); }; };
这种方式仍属于全局中间件,会对所有请求执行匹配判断,不如方案一高效精准。
内容的提问来源于stack exchange,提问作者Tony
相关产品推荐
相关产品推荐

