JWT tokens¶
A JWT (JSON Web Token) is a signed token that carries a JSON payload and an expiry time. Easy8 uses JWTs for service-to-service calls and for authenticating API requests without an API key.
Configuration¶
Set the EASY_JWT_SECRET environment variable. Services that share tokens, for example other containers in the same Docker environment, must use the same value. Without it, EasyExtensions::JWT.secret raises EasyExtensions::JWT::SecretNotSetError. Tokens are signed with HS256.
Encode and decode¶
EasyExtensions::JWT.encode(payload, expiration: nil) turns a hash into a token. The default expiration is 15 minutes. If the payload has no user_id, the ID of User.current is added.
# default expiration
token = EasyExtensions::JWT.encode({ key: "value" })
# custom expiration
token = EasyExtensions::JWT.encode({ key: "value" }, expiration: 5.minutes.from_now)
EasyExtensions::JWT.decode(token) returns the payload as an ActiveSupport::HashWithIndifferentAccess. An invalid or expired token raises JWT::DecodeError.
Authenticate a user with a JWT¶
EasyExtensions::JWT::GenerateAuthToken creates a token that authenticates a user without an API key or password. The payload holds user_id and user_login. The user defaults to User.current.
token = EasyExtensions::JWT::GenerateAuthToken.call(user: User.find(1))
# token for the current user
token = EasyExtensions::JWT::GenerateAuthToken.call
Send the token in the Authorization header with the Bearer prefix:
The token authenticates only endpoints that declare accept_api_auth in their controller, and only when the REST API is enabled in the settings. No other code is needed: ApplicationController#find_current_user resolves the user from the token (jwt_user), and only for active users.