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
payload = {
"sub": "user_12345",
"name": "Alice Wonderland",
"role": "admin",
"iat": now
}
# 2. Get your secret key securely
secret = getenv("JWT_SECRET")
# 3. Sign the token (default algorithm: HS256)
token = jwt_sign(payload, secret)
# Option: Set expiration (e.g., 1 hour from now)
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.
result = jwt_verify(token, secret)
if result["error"] == true
# Handle invalid token
print("Auth Error:", result["message"])
else
# Token is valid, access claims
user_id = result["sub"]
print("Authenticated User:", user_id)
end
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.