Sessions and credentials
This page explains how Behemoth remembers a signed-in user, and how it handles the secrets that prove who a user is: passwords, tokens, and codes. Read How Behemoth fits together first.
Behemoth keeps no raw secret. It stores a hash of every token and code, a salted hash of every password, and encrypted copies of the few values it must read back. A copy of your database does not contain a usable token or password.
Sessions #
A sign-in creates a session and gives the client a token for it. The client sends the token with later requests, and Behemoth resolves it back to the session. The session lives in your database, and optionally in a key-value store that serves as a cache.
A request that carries a token Behemoth cannot use gets a 401 response with a code that tells the client what to do:
| Code | Meaning |
|---|---|
session_missing | The request has no token. |
session_invalid | The token belongs to no session. |
session_expired | The session ended because its time ran out. |
session_revoked | The session was ended on purpose, for example by a sign-out on another device. |
session_pending | The user signed in with a first factor and the session waits for a second one. |
Session lifetime #
Set the session rules in BootConfig.Session. Every field is optional. The following table lists the ones you are most likely to change:
| Field | Default | What it controls |
|---|---|---|
ExpiresIn | 7 days | How long a session lasts. |
UpdateAge | Off | Rolling expiration: a session in use is extended once less than this much time is left. |
FreshAge | 15 minutes | How long after a sign-in a session counts as fresh. |
MaxConcurrent | No limit | How many sessions a user can use at once. |
CaptureIPAndAgent | Off | Whether to record the client's IP address and user agent on the session. |
Without UpdateAge, a session ends ExpiresIn after its sign-in, however much it is used. With it, a user who stays active stays signed in. Keep UpdateAge well below ExpiresIn, or Behemoth writes to the database on every request.
A fresh session is one that the user created recently. Use it for sensitive actions such as changing a password, where an old session is not proof enough. See Fresh sessions.
Token delivery #
The delivery decides how the token travels between Behemoth and the client. Set it in BootConfig.Router.Carrier:
| Delivery | The client receives the token in | Choose it for |
|---|---|---|
DeliveryCookie (default) | A cookie that the browser sends by itself | A browser application served from the same site as the API |
DeliveryHeader | The Set-Auth-Token header, sent back as Authorization: Bearer | Mobile apps, command-line tools, and other servers |
DeliveryBody | The JSON body of the sign-in response, sent back as a bearer token | Clients that cannot read response headers, such as a script on another origin |
DeliveryBoth | The cookie and the header | An application with browser and non-browser clients |
The following example gives the token to the client in a header and extends active sessions:
ac, err := engine.Boot(
ctx,
app,
db,
engine.BootConfig{
Crypto: cryptoCfg,
Session: core.SessionConfig{
ExpiresIn: 7 * 24 * time.Hour,
UpdateAge: 24 * time.Hour,
},
Router: httpapi.RouterConfig{
Carrier: httpapi.TokenCarrierConfig{
Delivery: httpapi.DeliveryHeader,
},
},
},
)
if err != nil {
log.Fatal(err)
}A browser attaches the cookie to every request to your API, including one that a page on another site caused. Under the cookie deliveries, Behemoth refuses a state-changing request from an origin it does not trust. Set RouterConfig.BaseURL to the address where browsers reach Behemoth, and list any other front end in RouterConfig.TrustedOrigins. See Cross-site requests.
Protect your own routes #
Behemoth authenticates every request before its route runs. To require a signed-in user on a route of your own, add the httpapi.RequireSession middleware to the route, as in the Routes method of a plugin. A request without a valid session never reaches your handler.
func (p *Plugin) Routes() []httpapi.Route {
return []httpapi.Route{
{
Method: http.MethodGet,
Path: "/me",
Handler: me,
Middlewares: []httpapi.Middleware{
httpapi.RequireSession(),
},
},
}
}
func me(rctx *httpapi.RequestContext) error {
caller := identity.CallerFrom(rctx.Ctx)
session, ok := caller.Session()
if !ok {
return errs.NewSessionError(
"me",
errs.CodeSessionMissing,
nil,
)
}
return rctx.Response.JSON(
http.StatusOK,
behemoth.M{"user_id": session.UserID},
)
}For an action that needs a recent sign-in, use httpapi.RequireFreshSession(ac.SessionManager) instead. The caller that the handler reads is described in Callers and permissions.
Session tokens for other services #
A service that does not share your process, such as a worker or an API in another language, cannot look up a session. For that case, Behemoth can exchange a session for a short-lived signed token (a JWT). The client posts to POST /session/token, receives a token valid for 15 minutes, and sends it to the service. The service checks the token against the public keys at /.well-known/jwks.json, so it never calls Behemoth.
Session tokens are off until you name the services that accept them in BootConfig.JWT. See Session tokens for the setup and routes, and JWT verification for checking a token in another Go service.
Credentials #
A credential is a secret that proves a user's identity or grants a step in a flow. Behemoth treats each kind differently, so that no stored value is useful to an attacker who copies it:
| Credential | Used for | What the database holds |
|---|---|---|
| Password | Sign-in with email, username, or phone number | An Argon2id hash, made with a secret value only your application knows |
| Session token | Every request after sign-in | A hash of the token |
| One-time token | A link in an email, such as a magic link, an address confirmation, or a password reset | A hash of the token. The token expires and works once. |
| One-time code | A short numeric code sent by text message | A hash of the code |
| Recovery code | Passing the second factor when the user cannot use their usual method | A hash of the code |
| Two-factor secret | Generating authenticator app codes | An encrypted copy, because Behemoth must read it back to check a code |
The raw value of a token or code exists only in the response that creates it, or in the message you send. If a user loses it, Behemoth cannot show it again. It issues a new one.
Password hashing #
Hashing a password is slow and uses memory on purpose, to make guessing expensive. With the default settings, one hash holds 64 MiB while it runs. A burst of sign-ins could exhaust the memory of your process, so Behemoth limits how many hashes run at once. A request over the limit waits briefly, and then gets a 503 response with the code server_busy and a Retry-After header.
Tune both in BootConfig.Crypto: Password sets the Argon2id parameters, and PasswordLimit sets the number of concurrent hashes and the wait. The limit applies to each process, so each replica of a deployment has its own.
The master secret #
Every key that Behemoth uses comes from one master secret that you supply in crypto.Config.Secrets. It must be hex-encoded and at least 32 bytes once decoded. Generate one with openssl rand -hex 32, and keep it out of your repository and your database.
Behemoth derives a separate key for each job: hashing passwords, hashing tokens, encrypting stored values, and signing JWTs. A key made for one job does not work for another, so one leaked signature or hash does not weaken the rest.
secrets := crypto.StaticSecretSource{
Secrets: map[int]string{
1: os.Getenv("BEHEMOTH_SECRET"),
},
Current: 1,
}Rotate the secret #
A secret has a version number. New hashes and encrypted values use the current version, and each one records the version that made it. To rotate, add the new secret as a new version and make it current. Keep the old versions in the map, so that existing hashes, tokens, and encrypted values keep working.
secrets := crypto.StaticSecretSource{
Secrets: map[int]string{
1: os.Getenv("BEHEMOTH_SECRET_V1"),
2: os.Getenv("BEHEMOTH_SECRET_V2"),
},
Current: 2,
}StaticSecretSource reads the secrets once, so a rotation needs a restart. A source that supports watching applies a new version while the application runs.
Behemoth makes password hashes with a key derived from the master secret. If you replace the secret instead of adding a version, no existing password verifies, sessions and tokens stop working, and encrypted values become unreadable. Keep the old version until nothing that it made is in use. For session tokens that other services check, keep it at least as long as the token lifetime.
Next steps #
To go deeper, read the following pages:
- Sessions: Every setting, cookie attribute, and sign-in response.
- Two-factor authentication: Add a second factor to sign-in.
- Email and password: Configure password rules and the hashing limit.
- How Behemoth fits together: Where sessions fit in the life of a request.