github.com/lestrrat-go/jwx library.
Installation
Install the required dependency:- JWKS fetching and caching
- JWT parsing and verification
- Support for Ed25519, RSA, and ECDSA algorithms
Basic Example
Here’s a complete example of extracting and verifying a user from an HTTP request:auth/verify.go
HTTP Handler Example
Use the verification logic in an HTTP handler:handlers/profile.go
Middleware Pattern
Create reusable middleware to protect routes:middleware/auth.go
main.go
Production Configuration
For production, use environment variables for the JWKS URL:config/config.go
auth/verify.go
Error Handling
Handle different error cases appropriately:handlers/profile.go
Complete Example Server
Here’s a complete server implementation:main.go
Testing
Test your JWT verification:auth/verify_test.go
Environment Variables
Create a.env file for development:
.env
Common Issues
'invalid signature' error
'invalid signature' error
Ensure the JWKS URL is correct and matches your Better Auth instance:Test the JWKS endpoint:
'token expired' error
'token expired' error
JWTs have a limited lifetime. Ensure your frontend refreshes tokens before they expire. The
api-client.ts handles this automatically with a 10-second buffer.Missing user claims (email, name)
Missing user claims (email, name)
Use
token.Get() to extract custom claims:Next Steps
Python Example
See how to implement JWT verification in Python with Flask
Express Example
Learn how to verify JWTs in Express.js with jose