Laravel中使用L5-Swagger配置Bearer Token时出现P.forEach错误
Laravel L5-Swagger Sanctum Bearer Token授权报错解决
问题场景
Laravel项目中使用l5-swagger集成Swagger文档,通过Bearer Token实现Sanctum身份验证,但设置令牌后调用需授权的API时,Swagger UI抛出TypeError: P.forEach is not a function错误。
依赖版本
"darkaonline/l5-swagger": "^8.5", "zircote/swagger-php": "^4.8"
报错信息
TypeError: P.forEach is not a function at applySecurities (build-request.js:106:12) at buildRequest (build-request.js:16:9) at Object.execute_buildRequest [as buildRequest] (index.js:249:11) at actions.js:454:24 at index.js:174:16 at redux.mjs:331:12 at wrap-actions.js:33:10 at Object.newAction (system.js:175:26) at Object.executeRequest (system.js:487:17) at actions.js:501:22 (anonymous) @ system.js:490 (anonymous) @ actions.js:501 (anonymous) @ index.js:174 (anonymous) @ redux.mjs:331 (anonymous) @ wrap-actions.js:9 newAction @ system.js:175 (anonymous) @ system.js:487 handleValidationResultPass @ execute.jsx:66 handleValidationResult @ execute.jsx:80 onClick @ execute.jsx:90
现有配置
l5-swagger配置(config/l5-swagger.php)
'securityDefinitions' => [ 'securitySchemes' => [ 'sanctum' => [ // 安全方案唯一名称 'securityDefinition' => "Bearer", 'type' => 'apiKey', // 有效值为"basic", "apiKey"或"oauth2" 'description' => 'Enter token in format (Bearer <token>)', 'name' => 'Authorization', // 要使用的请求头或查询参数名称 'in' => 'header', // API密钥位置,有效值为"query"或"header" ], ], 'security' => [ [ 'sanctum' => [] ], ], ],
控制器OA注解
/** * @OA\Post( * path="/manager/user/add", * tags={"Manager"}, * security={"sanctum": {}}, * @OA\Response(response="200", description="An example resource",@OA\JsonContent()), * @OA\Response(response="401", description="unAutosize",@OA\JsonContent()), * @OA\RequestBody( * required=true, * @OA\JsonContent( * required={"name", "email","password"}, * @OA\Property( * property="name", * type="string", * ), * @OA\Property( * property="email", * type="string", * ), * @OA\Property( * property="password", * type="string" * ) * ))) * ) */
错误原因
l5-swagger 8.x基于OpenAPI 3.0规范,现有配置中使用了OpenAPI 2.0的遗留字段securityDefinition,该字段在OpenAPI 3中已废弃。Swagger UI解析时将此字段误认为可遍历的数组,实际却是字符串,因此抛出forEach is not a function类型错误。
解决方案
1. 修改l5-swagger安全配置
将config/l5-swagger.php中的securityDefinitions替换为符合OpenAPI 3规范的Bearer认证配置:
'securityDefinitions' => [ 'securitySchemes' => [ 'sanctum' => [ 'type' => 'http', // HTTP认证类型 'scheme' => 'bearer', // Bearer认证方案 'bearerFormat' => 'JWT', // 可选:指定令牌格式,如JWT 'description' => '输入格式为:Bearer <token>', ], ], 'security' => [ [ 'sanctum' => [] ], ], ],
若坚持使用apiKey类型(不推荐,Bearer更标准),只需移除错误的securityDefinition字段:
'sanctum' => [ 'type' => 'apiKey', 'description' => '输入格式为:Bearer <token>', 'name' => 'Authorization', 'in' => 'header', ],
2. 重新生成Swagger文档
执行Artisan命令清除旧文档并生成新规范文件:
php artisan l5-swagger:generate
3. 验证效果
刷新Swagger UI页面,重新输入Bearer Token并调用API,错误即可消除。
内容的提问来源于stack exchange,提问作者m mardani
相关产品推荐
相关产品推荐

