Better Auth in Rust

Sessions

Session lifecycle, token handling, and session management endpoints.

The SessionManagementPlugin provides endpoints for querying, listing, and revoking sessions. Sessions are created automatically during sign-up and sign-in.

Setup

use better_auth::plugins::SessionManagementPlugin;

let auth = BetterAuth::new(config)
    .database(database)
    .plugin(SessionManagementPlugin::new())
    .build()
    .await?;

Plugin Options

OptionTypeDefaultDescription
enable_session_listingbooltrueAllow listing all user sessions
enable_session_revocationbooltrueAllow revoking sessions
require_authenticationbooltrueRequire auth for all endpoints

Authentication Methods

Session tokens can be sent via Bearer header or cookie:

Authorization: Bearer session_abc123...
Cookie: better-auth.session-token=session_abc123...

The cookie name is configurable via SessionConfig::cookie_name.

Get Current Session

GET /get-session
Authorization: Bearer <token>

Response

{
  "session": {
    "id": "uuid",
    "token": "session_abc123...",
    "userId": "uuid",
    "expiresAt": "2024-01-08T00:00:00Z",
    "createdAt": "2024-01-01T00:00:00Z",
    "updatedAt": "2024-01-01T00:00:00Z",
    "ipAddress": null,
    "userAgent": null
  },
  "user": {
    "id": "uuid",
    "email": "[email protected]",
    ...
  }
}

Returns 401 if the token is missing, invalid, or expired.

Sign Out

POST /sign-out
Authorization: Bearer <token>

Revokes the current session. Returns:

{
  "success": true
}

List Sessions

GET /list-sessions
Authorization: Bearer <token>

Returns all active sessions for the authenticated user:

{
  "sessions": [
    { "id": "uuid", "token": "session_...", "createdAt": "...", ... },
    { "id": "uuid", "token": "session_...", "createdAt": "...", ... }
  ]
}

Revoke a Specific Session

POST /revoke-session
Authorization: Bearer <token>
Content-Type: application/json
{
  "token": "session_to_revoke..."
}

Returns { "success": true }.

Revoke All Sessions

POST /revoke-sessions
Authorization: Bearer <token>

Revokes all sessions for the user, including the current one:

{
  "count": 3
}

Revoke Other Sessions

POST /revoke-other-sessions
Authorization: Bearer <token>

Revokes all sessions except the current one:

{
  "count": 2
}

Using Sessions in Axum Handlers

With the axum feature, use the CurrentSession extractor to access the authenticated user directly in your handler — no manual token parsing needed:

use better_auth::handlers::CurrentSession;
use better_auth::adapters::MemoryDatabaseAdapter;
use better_auth::AuthUser;
use axum::{Json, response::IntoResponse};

async fn profile(session: CurrentSession<MemoryDatabaseAdapter>) -> impl IntoResponse {
    Json(serde_json::json!({
        "user_id": session.user.id(),
        "session_token": session.session.token(),
    }))
}

Use OptionalSession for routes that should work for both authenticated and anonymous users. See Axum Integration for full details.

Session Configuration

Session behavior is configured via AuthConfig:

use better_auth::{AuthConfig, SameSite};
use std::time::Duration;

let mut config = AuthConfig::new("secret...");
config.session.expires_in = Duration::hours(24 * 7);        // 7 days
config.session.cookie_name = "better-auth.session-token".to_string();
config.session.cookie_secure = true;                         // HTTPS only
config.session.cookie_http_only = true;                      // Block JavaScript access
config.session.cookie_same_site = SameSite::Lax;             // CSRF protection
OptionTypeDefaultDescription
session.expires_inDuration7 daysSession lifetime
session.cookie_nameStringbetter-auth.session-tokenCookie name
session.cookie_securebooltrueHTTPS-only cookie
session.cookie_http_onlybooltruePrevent JavaScript access
session.cookie_same_siteSameSiteLaxSameSite cookie policy

See Configuration Options for all session settings.

Session Lifecycle

  1. Creation: A session is created on successful sign-up, sign-in, or 2FA verification
  2. Storage: The session token and metadata are stored in the database
  3. Transmission: The token is returned in the response body and set as a cookie
  4. Validation: On each authenticated request, the token is verified against the database
  5. Expiration: Sessions automatically expire after the configured duration
  6. Revocation: Sessions can be explicitly revoked via the API

Session Fields

FieldDescription
idUnique session identifier
tokenSession token (sent as cookie or Bearer token)
userIdID of the authenticated user
expiresAtSession expiration timestamp
createdAtWhen the session was created
updatedAtLast update timestamp
ipAddressClient IP address (if available)
userAgentClient User-Agent string (if available)
impersonatedByAdmin user ID if this is an impersonated session
activeOrganizationIdActive organization ID (if using Organization plugin)

Two-Factor Authentication

When 2FA is enabled for a user, the sign-in flow changes:

  1. User provides email/password — credentials are verified but no session is created
  2. A pending verification token is returned instead
  3. User must complete 2FA verification (TOTP, OTP, or backup code)
  4. Only after successful 2FA verification is a full session created

See Two-Factor Authentication for details.

Session Security

  • Token entropy: Tokens are generated using OsRng with sufficient entropy
  • Cookie security: Configure Secure, HttpOnly, and SameSite attributes appropriately
  • IP tracking: Client IP and User-Agent are stored for audit purposes
  • Multiple sessions: Users can have multiple active sessions across devices
  • Selective revocation: Revoke individual sessions, all sessions, or all except current

See Cookies and Security for more details.

On this page