← Back to Node.js | JavaScript | Main README
This project provides an AWS Lambda function implemented in Node.js to validate JWT tokens issued by Keycloak. The function uses the JWKS endpoint provided by Keycloak to fetch public keys dynamically for verifying RS256-signed tokens.
- Ensure you have a Keycloak server running.
- Create a
realmand aclientin Keycloak. Useconfidentialclient for server-to-server communication. - Obtain:
- Client ID
- Keycloak JWKS endpoint:
https://<keycloak-domain>/realms/<realm-name>/protocol/openid-connect/certs
-
File: index.js:
Contains the main AWS Lambda code for validating JWT tokens. -
Dependencies:
Install locally before deploying:
npm install jsonwebtoken jwks-rsa
Install the required libraries locally:
npm install jsonwebtoken jwks-rsa
- Include
index.jsand thenode_modulesfolder. - Zip the files:
zip -r lambda-keycloak.zip index.js node_modules
- Log in to the AWS Management Console.
- Create a new Lambda function or select an existing one.
- Upload the
lambda-keycloak.zipfile under "Function Code".
Pass the following event object when testing the Lambda function:
{
"headers": {
"Authorization": "Bearer <your-jwt-token>"
}
}Replace <your-jwt-token> with a valid JWT generated by Keycloak.
{
"statusCode": 200,
"body": "{\"message\":\"Token is valid\", \"user\":{\"sub\":\"1234abcd\",\"name\":\"John Doe\",\"email\":\"johndoe@example.com\"}}"
}{
"statusCode": 401,
"body": "{\"message\":\"Invalid or expired token\",\"error\":\"jwt malformed\"}"
}{
"statusCode": 401,
"body": "{\"message\":\"Missing Authorization header\"}"
}To generate a token from Keycloak:
- Log into Keycloak Admin Console.
- Navigate to your realm, then to your client's settings (client ID).
- Use Keycloak’s token endpoint:
- URL:
https://<keycloak-domain>/realms/<realm-name>/protocol/openid-connect/token - Method: POST
- Parameters:
grant_type:client_credentialsclient_id:<your-client-id>client_secret:<your-client-secret>
- URL:
Use the generated token for testing.
- Avoid hardcoding sensitive values like
client_idandissuerin the code. Use AWS Secrets Manager or Parameter Store to securely retrieve these values at runtime.
Extend token validation to verify roles, expiration (exp), and audience (aud) based on your requirements.
Integrate Lambda with AWS API Gateway to secure endpoints and validate incoming requests.
- Keycloak Documentation
- Node.js jsonwebtoken Library
- Node.js jwks-rsa Library
- AWS Lambda Documentation
- index.js: Lambda function code
- README.md: Documentation
- node_modules/: Installed dependencies
- lambda-keycloak.zip: Deployment package created via zip command
This Lambda function securely integrates with Keycloak for validating JWT tokens and supports serverless architectures running on AWS. Let me know if further configurations or advanced setups (like multi-realm support) are required!