Keycloak持续重定向至登录页问题排查求助
Hey Dominik, let's break down why you're hitting this redirect loop when accessing your API with a valid JWT on AWS—since your setup works locally, HTTPS and environment-specific configs are almost certainly the culprits. Here's a step-by-step troubleshooting guide:
1. Force Keycloak Middleware to Use Bearer-Only Mode (Critical Fix)
Your current setup uses a session store, which is designed for browser-based login flows. Since your frontend handles login and passes JWTs directly to the API, you need to tell the Keycloak connector to only validate Bearer tokens instead of trying to redirect unauthenticated requests to the login page.
Modify your Keycloak initialization code to add bearerOnly: true:
public init() { if (this.keycloak) { console.warn("Trying to init Keycloak again!"); return this.keycloak; } else { console.log("Initializing Keycloak..."); const memoryStore = new session.MemoryStore(); // @ts-ignore this.keycloak = new Keycloak({ store: memoryStore, bearerOnly: true // Add this line to disable login redirects }, this.keycloakConfig ); return this.keycloak; } }
Without this setting, the middleware will try to create a session for unauthenticated requests (even if you send a valid JWT) and redirect to Keycloak's login page—this is the most likely source of your loop.
2. Configure Express to Trust AWS Proxy Headers
AWS load balancers (like ALBs) terminate HTTPS traffic and forward requests to your EC2 instance over HTTP. If Express doesn't recognize this, it will detect the request as HTTP, and the Keycloak connector will reject the "insecure" request, triggering a redirect.
Add this line to your Express app setup:
app.set('trust proxy', true);
This tells Express to trust the X-Forwarded-Proto header sent by AWS, so it correctly identifies the original request as HTTPS.
3. Update Keycloak Client Configuration
Double-check your confidential client settings in Keycloak to match your production environment:
- Redirect URIs: Add your production API's HTTPS base URL (e.g.,
https://your-api-domain.com/*). Local URIs (http://localhost:xxx) won't work in AWS, and missing production URIs can cause Keycloak to invalidate tokens or redirects. - Web Origins: Set this to
*(for testing) or your frontend's domain to avoid CORS issues that might interfere with token validation. - SSL Required: Ensure this is set to
externalorall(under the "Advanced" tab) to enforce HTTPS for all production requests.
4. Validate Your JWT Token's Claims
Even if the token is syntactically valid, mismatched claims can cause validation failures. Use a tool like jwt.io to decode your production token and verify:
- Issuer (
iss): Should matchhttps://keycloak.myserver.com/auth/realms/examplerealm(exactly what's in yourkeycloakConfig). - Audience (
aud): Should include yourui-clientclient ID. - Expiration (
exp): Ensure the token hasn't expired.
5. Verify Network Connectivity Between AWS and Keycloak
Make sure your EC2 instance can reach your Keycloak server over HTTPS. Run this command on your AWS Linux machine:
curl https://keycloak.myserver.com/auth/realms/examplerealm/.well-known/openid-configuration
If this fails, check your AWS security groups/NACLs to ensure outbound traffic to port 443 is allowed, and that your Keycloak server isn't blocking traffic from your EC2's IP.
Bonus: Replace MemoryStore for Production (Optional)
While not the cause of your current issue, MemoryStore is not suitable for production—it will lose sessions when your server restarts or scales. For multi-instance deployments, use a persistent store like Redis or PostgreSQL.
Start with the first two fixes (bearerOnly and trust proxy) since those are the most common causes of this exact problem. Let me know if any of these steps resolve the issue, or if you need to share more details!
内容的提问来源于stack exchange,提问作者Dominik

