Skip to content

BFF Sessions

The BFF (Backend for Frontend) session package provides server-side session management with HTTP-only cookies for secure web applications.

Why BFF Sessions?

Traditional SPA architectures store tokens in browser storage (localStorage/sessionStorage), which exposes them to XSS attacks. BFF sessions keep tokens server-side:

Approach Token Location XSS Risk CSRF Risk
localStorage Browser High None
sessionStorage Browser High None
HTTP-only Cookie Server None Mitigated

Store Interface

type Store interface {
    // Create stores a new session.
    Create(ctx context.Context, session *Session) error

    // Get retrieves a session by ID.
    Get(ctx context.Context, id string) (*Session, error)

    // Update updates an existing session.
    Update(ctx context.Context, session *Session) error

    // Delete removes a session by ID.
    Delete(ctx context.Context, id string) error

    // DeleteByUserID removes all sessions for a user.
    DeleteByUserID(ctx context.Context, userID string) (int, error)

    // Touch updates the LastAccessedAt timestamp.
    Touch(ctx context.Context, id string) error

    // Cleanup removes expired sessions.
    Cleanup(ctx context.Context) (int, error)

    // Close closes the store.
    Close() error
}

Storage Backends

Memory Store

For development and single-server deployments:

store := bff.NewMemoryStore()

Ent Store

For SQL databases via Ent ORM:

sealer, err := bff.NewKeyringSealer("k1", map[string][]byte{"k1": sessionKey})
if err != nil {
    return err
}
store, err := bff.NewEntStore(bff.EntStoreConfig{
    Client: entClient, // implements bff.EntClientInterface
    Sealer: sealer,    // encrypts tokens and DPoP keys at rest
})
if err != nil {
    return err
}

See Ent Store for the client adapter and key rotation.

For production with Redis and security controls:

store, err := bff.NewOmniStorageStore(bff.OmniStorageConfig{
    Backend:         "redis",
    SiteID:          "myapp", // required for redis
    Sealer:          sealer,  // required for redis; see below
    RedisURL:        "rediss://:[email protected]:6379", // TLS and a password
    MaxSessionSize:  1024 * 1024, // 1MB
    DefaultTTL:      24 * time.Hour,
    CleanupInterval: 5 * time.Minute,
    KeyPrefix:       "myapp:session:",
})

Tokens and DPoP private keys are sealed before they reach Redis. Sealer is required for the redis backend (bff.ErrSealerRequired otherwise). Each session's data is encrypted with AES-256-GCM and bound to its session ID and SiteID, so a ciphertext copied to another record does not open. Two sealers are provided:

// Application-held keys, with key IDs for rotation (see below).
sealer, err := bff.NewKeyringSealer("k1", map[string][]byte{
    "k1": sessionKey, // 32 bytes, from your secret store
})

// Or a keyforge purpose key from the keys package, which versions and
// rotates keys itself.
sealer := bff.NewKeysSealer(sysKeys, "bff-session")
Rotating keyring keys

Every sealed value names the key that sealed it. A rotation keeps the active key N and the previous key N-1 in the ring and removes only N-2, and each step is its own deploy, so rolling back any deploy still opens every session written so far:

  1. Pre-stage k2. Add it to the ring while k1 stays active, and wait until every instance runs it: bff.NewKeyringSealer("k1", map[string][]byte{"k1": k1, "k2": k2}).
  2. Promote k2. Make it active and keep k1: bff.NewKeyringSealer("k2", map[string][]byte{"k1": k1, "k2": k2}). Rolling this deploy back returns to step 1, which still opens sessions sealed with k2.
  3. Next rotation. Pre-stage k3 with k1 still in the ring, then promote k3 with {"k2": k2, "k3": k3}. Sessions still sealed with k1 (N-2) no longer open and their users sign in again; a session is sealed again under the active key whenever it is updated, for example on token refresh.

Never add a new active key and drop the previous one in the same deploy.

Once a sealer is configured, sessions stored in plaintext are rejected and their users sign in again. InsecurePlaintext: true disables the requirement for local development only.

OmniStorage Configuration

Field Description Default
Backend "memory" or "redis" "memory"
RedisURL Redis connection URL. A server that is not on loopback must use TLS (rediss://) with certificate verification and a password Required for redis
AllowInsecureRedis Permit a non-loopback Redis without TLS, a password or certificate verification, such as a local container network (development only; logs a warning) false
SiteID Tags every session with this application; a session tagged for another site is not found Required for redis
Sealer Encrypts tokens and DPoP keys at rest (NewKeyringSealer, NewKeysSealer) Required for redis
InsecurePlaintext Store secrets unencrypted without a Sealer (development only) false
MaxSessionSize Max session size in bytes 1MB
DefaultTTL Session lifetime 24 hours
CleanupInterval Cleanup frequency 5 minutes
KeyPrefix Prefix of session keys and the per-user session index "session:<SiteID>:"
ControlOptions Logger, violation handler None

With Observability

import omnisession "github.com/plexusone/omnistorage-core/session"

store, err := bff.NewOmniStorageStore(bff.OmniStorageConfig{
    Backend:        "redis",
    SiteID:         "myapp", // required for redis
    Sealer:         sealer,  // required for redis
    RedisURL:       os.Getenv("REDIS_URL"),
    MaxSessionSize: 1024 * 1024,
    ControlOptions: []omnisession.ControlOption{
        omnisession.WithLogger(slog.Default()),
        omnisession.WithViolationHandler(func(ctx context.Context, event omnisession.ViolationEvent) {
            // Record metric
            metrics.SessionViolations.Inc(event.Type)

            // Alert on abuse
            if event.Type == omnisession.ViolationSizeExceeded {
                alerting.Warn("Session size exceeded", event)
            }
        }),
    },
})
cookies := bff.NewCookieManager(bff.CookieConfig{
    Name:     "__Host-myapp_session", // Default: bff.DefaultCookieName ("__Host-sf_session")
    Path:     "/",                    // Required for a __Host- cookie
    SameSite: http.SameSiteStrictMode,
    MaxAge:   86400,                  // 24 hours in seconds
})

The cookie is always HttpOnly, and Secure unless AllowInsecure is set for plain-HTTP development (the default name is then bff.InsecureCookieName, sf_session, because browsers reject a __Host- cookie that is not Secure). The cookie is always host-only: CookieConfig has no Domain field, because a Domain would share the session with every subdomain, any of which could then read or overwrite it. CookieConfig.Validate (which bff.NewHandler calls) rejects a __Host- name with another Path or without Secure.

Middleware

Required Session

Requires authentication, returns 401 if no session:

router.Use(bff.SessionMiddleware(store, cookies))

// In handler
session := bff.SessionFromContext(r.Context())
// session is guaranteed non-nil

Optional Session

Loads session if present, but doesn't require it:

router.Use(bff.OptionalSessionMiddleware(store, cookies))

// In handler
session := bff.SessionFromContext(r.Context())
if session == nil {
    // Not logged in
}

Session Operations

Create Session (Login)

func handleOAuthCallback(w http.ResponseWriter, r *http.Request) {
    // Exchange code for tokens
    tokens, err := oauth.Exchange(ctx, code)

    // Create session
    session := &bff.Session{
        ID:                    bff.GenerateSessionID(),
        UserID:                user.ID,
        OrganizationID:        &user.DefaultOrgID,
        AccessToken:           tokens.AccessToken,
        RefreshToken:          tokens.RefreshToken,
        AccessTokenExpiresAt:  tokens.Expiry,
        IPAddress:             r.RemoteAddr,
        UserAgent:             r.UserAgent(),
        CreatedAt:             time.Now(),
        ExpiresAt:             time.Now().Add(24 * time.Hour),
    }

    if err := store.Create(ctx, session); err != nil {
        // Handle error
    }

    // Set session cookie
    cookies.Set(w, session.ID)

    http.Redirect(w, r, "/dashboard", http.StatusFound)
}

Get Current Session

func handleGetSession(w http.ResponseWriter, r *http.Request) {
    session := bff.SessionFromContext(r.Context())

    json.NewEncoder(w).Encode(map[string]any{
        "user_id":         session.UserID,
        "organization_id": session.OrganizationID,
        "expires_at":      session.ExpiresAt,
    })
}

Update Session (Token Refresh)

func refreshTokens(ctx context.Context, session *bff.Session) error {
    // Refresh OAuth tokens
    newTokens, err := oauth.Refresh(ctx, session.RefreshToken)
    if err != nil {
        return err
    }

    // Update session
    session.AccessToken = newTokens.AccessToken
    session.RefreshToken = newTokens.RefreshToken
    session.AccessTokenExpiresAt = newTokens.Expiry
    session.UpdatedAt = time.Now()

    return store.Update(ctx, session)
}

Delete Session (Logout)

func handleLogout(w http.ResponseWriter, r *http.Request) {
    session := bff.SessionFromContext(r.Context())

    // Delete from store
    store.Delete(ctx, session.ID)

    // Clear cookie
    cookies.Clear(w)

    http.Redirect(w, r, "/", http.StatusFound)
}

Logout All Devices

func handleLogoutAllDevices(w http.ResponseWriter, r *http.Request) {
    session := bff.SessionFromContext(r.Context())

    // Delete all sessions for user
    count, err := store.DeleteByUserID(ctx, session.UserID.String())

    // Clear current cookie
    cookies.Clear(w)

    json.NewEncoder(w).Encode(map[string]any{
        "logged_out_sessions": count,
    })
}

Error Handling

session, err := store.Get(ctx, sessionID)
if err != nil {
    switch {
    case errors.Is(err, bff.ErrSessionNotFound):
        // Session doesn't exist
        http.Error(w, "Session not found", http.StatusUnauthorized)
    case errors.Is(err, bff.ErrSessionExpired):
        // Session expired
        cookies.Clear(w)
        http.Error(w, "Session expired", http.StatusUnauthorized)
    default:
        // Internal error
        http.Error(w, "Internal error", http.StatusInternalServerError)
    }
}

Integration with OAuth

See OAuth documentation for integrating BFF sessions with OAuth providers.

// OAuth callback handler
func handleOAuthCallback(w http.ResponseWriter, r *http.Request) {
    // 1. Validate state parameter
    // 2. Exchange code for tokens
    // 3. Get or create user
    // 4. Create BFF session with tokens
    // 5. Set session cookie
    // 6. Redirect to app
}