如何在KONG中实现外部认证?独立JWT微服务场景实现方法
Hey there! Let's walk through exactly how to set up this flow where Kong checks your standalone auth service for valid JWT tokens before forwarding requests to your target service—no built-in JWT plugin required. Here's a step-by-step breakdown tailored to your setup:
1. 确认你的认证服务已在Kong中注册
Since you already have user registration/login working, I assume your auth microservice is already registered as a Kong Service. First, make sure you have a dedicated token validation endpoint (like /auth/verify) on your auth service:
- This endpoint should accept the
Authorizationheader from incoming requests - Return
200 OKif the token is valid, and401 Unauthorized/403 Forbiddenif it's invalid or expired
If you haven't already mapped this endpoint to a Kong Route, run these commands (adjust values to match your setup):
# Create a Service for your auth microservice (if not already done) kong service create --name auth-service --url http://your-auth-service-host:port # Create a Route for the token validation endpoint kong route create --name auth-verify-route --service auth-service --paths /auth/verify
2. Use Kong's pre-function Plugin for Pre-Request Validation
Kong's pre-function plugin lets you run custom Lua logic before a request is forwarded to the target service. This is perfect for adding our auth check. We'll write Lua code to:
- Extract the JWT from the request header
- Call your auth service's validation endpoint
- Block the request if validation fails, or let it proceed if it passes
Add the Plugin to Your Target Service
Run this command to attach the pre-function plugin to the target service you want to protect (replace target-service with your actual service name):
kong plugin add pre-function --service target-service --config access=" -- Step 1: Grab the Authorization header local auth_header = kong.request.get_header('Authorization') if not auth_header then kong.response.exit(401, { message = 'Authorization header is missing' }) end -- Step 2: Extract the Bearer token (adjust regex if your format differs) local token = string.match(auth_header, 'Bearer%s+(.+)') if not token then kong.response.exit(401, { message = 'Invalid Authorization header format (use "Bearer <token>")' }) end -- Step 3: Call your auth service's validation endpoint local auth_response = kong.client.proxy_request({ method = 'POST', -- Use GET if your validation endpoint uses GET path = '/auth/verify', headers = { ['Authorization'] = auth_header -- Pass the original token to auth service }, body = {} -- Add request body here if your validation endpoint requires it }) -- Step 4: Check if validation passed if auth_response.status ~= 200 then -- Forward the auth service's error response to the user kong.response.exit(auth_response.status, auth_response.body, auth_response.headers) end "
Quick Code Explanation:
- We first validate the presence and format of the
Authorizationheader kong.client.proxy_requestmakes an internal call to your auth service (no external network hop if Kong and your auth service are in the same cluster)- If the auth service returns anything other than 200, we immediately send that error back to the user and stop the request from reaching the target service
- If validation passes, Kong automatically proceeds to forward the request to your target service
3. Test the Flow
Verify everything works as expected with these test cases:
- Send a request without an
Authorizationheader: Kong should return a 401 with your custom message - Send a request with an invalid token: Kong will pass it to your auth service, then return the auth service's 401/403 response
- Send a request with a valid token: Kong will validate it, then forward the request to your target service and return its response
Pro Tips for Production
- Cache Validations: Reduce load on your auth service by adding Kong's
proxy-cacheplugin to cache valid token results (use the token as the cache key, and set the TTL to match your token's expiration time) - Timeout Handling: Add logic to handle auth service timeouts (e.g., return a 503 if the auth service is unreachable)
- Restrict Auth Service Access: Make sure your auth service's validation endpoint is only accessible from Kong (use network policies or firewall rules)
内容的提问来源于stack exchange,提问作者adnanmuttaleb

