Authentication with JWT
Implement secure, stateless authentication for your APIs and web applications using JSON Web Tokens.
Secure by Default
SoliLang includes first-class support for JWT (JSON Web Token). Unlike session-based auth, JWTs are stateless, making them perfect for microservices, mobile apps, and modern Single Page Applications (SPAs).
1 Creating Tokens
Use the jwt_sign function to create a signed token. You can include any custom claims in the payload.
// 1. Define your payload
let payload = {
"sub": "user_12345",
"name": "Alice Wonderland",
"role": "admin",
"iat": now()
};
// 2. Get your secret key securely
let secret = getenv("JWT_SECRET");
// 3. Sign the token (default algorithm: HS256)
let token = jwt_sign(payload, secret);
// Option: Set expiration (e.g., 1 hour from now)
let token_with_exp = jwt_sign(
payload,
secret,
{ "expires_in": 3600 }
);
2 Verifying Tokens
Verify incoming tokens using jwt_verify. This function checks the signature and expiration automatically.
let result = jwt_verify(token, secret);
if result["error"] == true {
// Handle invalid token
print("Auth Error:", result["message"]);
return { "error": "Unauthorized" };
} else {
// Token is valid, access claims
let user_id = result["sub"];
print("Authenticated User:", user_id);
}
Security Warning
Never hardcode your JWT_SECRET in your source code. Always use environment variables (.env) or a secure secrets manager. If your secret is compromised, all issued tokens become insecure.
Ready to see it in action?
Check out the live demo to experience the authentication flow, including login and protected routes.