Krakend JWT认证未校验受保护API,寻求解决办法
问题原因
你当前配置里的auth/signer组件是用来对后端返回的Token进行签名的,并非用于验证请求头中的JWT Token。这就是为什么不带Token也能访问受保护接口的核心原因——该接口根本没开启请求Token校验逻辑。
解决方案
要实现接口的JWT认证保护,需要在/login_with_signer接口的extra_config中添加auth/validator配置,用于校验请求头里的Authorization Token。
修改后的krakend.json关键配置
{ "$schema": "https://www.krakend.io/schema/v3.json", "version": 3, "name": "RestApiGateway", "timeout": "300000ms", "cache_ttl": "4000s", "port": 8080, "output_encoding": "json", "extra_config": { "router": { "return_error_msg": true } }, "endpoints": [ { "endpoint": "/login_with_signer", "method": "POST", "extra_config": { "security/cors": { "allow_origins": ["*"], "allow_methods": ["GET","HEAD","POST"], "expose_headers": ["Content-Length","Content-Type"], "allow_headers": ["Origin","Authorization","Content-Type"], "max_age": "12h", "allow_credentials": false, "debug": false }, // 新增JWT请求验证配置 "auth/validator": { "alg": "HS256", "kid": "sim2", "jwk_url": "http://localhost:4500/symmetric.json", "disable_jwk_security": true, "operation_debug": true, "header_name": "Authorization", "token_type": "Bearer" }, // 若仍需对后端返回的Token签名,保留此配置 "auth/signer": { "alg": "HS256", "kid": "sim2", "keys_to_sign": ["access_token","refresh_token"], "cache": false, "jwk_url": "http://localhost:4500/symmetric.json", "disable_jwk_security": true, "operation_debug": true } }, "backend": [ { "url_pattern": "/api/test", "method": "POST", "host": ["http://localhost:4500"] } ] }, // 以下/login接口配置保持不变 { "endpoint": "/login", "method": "POST", "extra_config": { "security/cors": { "allow_origins": ["*"], "allow_methods": ["GET","HEAD","POST"], "expose_headers": ["Content-Length","Content-Type"], "allow_headers": ["Origin","Authorization","Content-Type"], "max_age": "12h", "allow_credentials": false, "debug": false } }, "backend": [ { "url_pattern": "/api/login", "method": "POST", "host": ["http://localhost:4500"] } ] } ] }
额外检查项
- 确认
symmetric.json中的k值是你Node.js项目里jsonwebtoken库生成Token时使用的密钥的Base64编码(当前值and0X3NlY3JldGU解码后为jwt_secret,需与代码中的secret参数完全一致) - 修改配置后必须重启Krakend服务才能生效
- 测试时,合法请求需携带请求头
Authorization: Bearer <你的JWT Token>,不带Token或Token无效时,Krakend会返回401/403错误
内容的提问来源于stack exchange,提问作者Subham
相关产品推荐
相关产品推荐

