browsersession

package
v0.19.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package browsersession protects a browser UI with an OIDC login and a backend-for-frontend (BFF) session.

The browser never holds a usable token. After login the access token, the refresh token and the access token's expiry are each stored in their own AES-GCM encrypted, HttpOnly, SameSite=Lax cookie. On every API request the server decrypts the access token and promotes it to an Authorization header, so the API behind it validates a bearer token exactly as it does for a machine caller. A token close to expiry is refreshed on the way through.

NewApp wires the pieces together. They are also exported for services that need a different arrangement:

  • CookieSet reads, writes and clears the encrypted session cookies.
  • AuthHandler serves login, the OIDC callback, logout and a public config document.
  • CookieAuthMiddleware promotes the session cookie to an Authorization header, and RefreshMiddleware refreshes a token that is about to expire.
  • SPAHandler serves a single-page app, and SessionGuard redirects a browser without a session to login.

Cookies and CSRF

The session cookies are SameSite=Lax, so a browser does not attach them to a cross-site POST, PUT, PATCH or DELETE. State-changing API routes must therefore not be reachable by GET. Logout is POST only and does nothing without a session cookie, so another site cannot sign a user out.

The session cookie is not a bearer token: its value is ciphertext, and its default name is not one a JWT middleware reads. A machine API on the same origin should accept the Authorization header only, which is the default for server.OAuth2ValidatorHandler.

Index

Examples

Constants

View Source
const (
	// DefaultTokenCookieName is the name of the encrypted access-token cookie.
	DefaultTokenCookieName = "bff_session"
	// DefaultRefreshCookieName is the name of the encrypted refresh-token cookie.
	DefaultRefreshCookieName = "bff_refresh"
	// DefaultExpiryCookieName is the name of the encrypted token-expiry cookie.
	DefaultExpiryCookieName = "bff_expiry"
)

Default session cookie names. They are deliberately different from the cookie names read by this module's other middleware ("auth_token" and oidc.DefaultTokenCookieName), so a session cookie is never mistaken for a bearer token.

Variables

This section is empty.

Functions

func CookieAuthMiddleware

func CookieAuthMiddleware(cookies *CookieSet) func(http.Handler) http.Handler

CookieAuthMiddleware promotes the session cookie to an Authorization: Bearer header, so that JWT validation further down the chain sees the session's access token. A request without a readable session is rejected with 401.

A request that already carries an Authorization header is rejected with 400: on a browser-facing route the session cookie is the only accepted credential, and a caller must not be able to choose which one is checked.

func RefreshMiddleware

func RefreshMiddleware(cookies *CookieSet, window time.Duration, refresh RefreshFunc) func(http.Handler) http.Handler

RefreshMiddleware refreshes a session that expires within window. The new tokens are written back to the session cookies, and the Authorization header of the current request is updated so JWT validation sees the new access token. It runs after CookieAuthMiddleware.

A session without a refresh token or a known expiry is passed through unchanged. When the refresh itself fails the session is cleared and the request is rejected with 401, so the browser app sends the user to login.

Concurrent requests can each see an expiring token and each try to refresh it. With a provider that rotates refresh tokens the second attempt fails and ends the session. A per-session refresh lock would avoid that.

func SPAHandler

func SPAHandler(staticFS fs.FS) http.Handler

SPAHandler serves a single-page app from staticFS. A path that names a file is served as that file. Any other path is served index.html, so the app's client-side routes survive a page reload.

func SessionGuard

func SessionGuard(cookies *CookieSet, loginPath string, window time.Duration, refresh RefreshFunc) func(http.Handler) http.Handler

SessionGuard redirects a browser without a readable session to loginPath, and refreshes a session that expires within window. It is for pages, where a redirect is the useful answer; API routes use CookieAuthMiddleware and RefreshMiddleware, which answer 401. A nil refresh disables refreshing.

Types

type App

type App struct {
	// Auth serves /login, /callback, /logout and /config. See AuthHandler.
	Auth http.Handler
	// UI serves the single-page app to browsers with a session and redirects
	// the rest to login.
	UI http.Handler
	// API is the caller's API handler behind the session: the session cookie
	// is promoted to an Authorization header and refreshed when due.
	API http.Handler
}

App is the set of handlers that make up a browser session app. Mount each under its own path prefix, with the prefix stripped.

func NewApp

func NewApp(cfg Config, apiHandler http.Handler, staticFS fs.FS) (*App, error)

NewApp wires a browser session around apiHandler and the single-page app in staticFS.

apiHandler receives each request with the session's access token in the Authorization header. It must validate that token itself, typically with server.OAuth2ValidatorHandler followed by principal extraction: NewApp checks that a session exists, not what the session is allowed to do.

Example

ExampleNewApp protects a single-page app and its API with a browser session. A real deployment mounts App.Auth, App.UI and App.API under path prefixes of one server. The example mounts them on one mux, signs in against a mock identity provider and calls the API with the session cookies.

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing/fstest"

	"github.com/dioad/auth/http/browsersession"
	oidcmw "github.com/dioad/auth/http/middleware/oidc"
	"github.com/dioad/auth/testutil"
)

func main() {
	idp, err := testutil.NewMockIDP()
	if err != nil {
		fmt.Println(err)
		return
	}
	defer idp.Close()

	// The API behind the session sees an ordinary bearer token. A real API
	// validates it, for example with server.OAuth2ValidatorHandler.
	api := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = fmt.Fprintln(w, "bearer token present:", strings.HasPrefix(r.Header.Get("Authorization"), "Bearer "))
	})
	staticFS := fstest.MapFS{"index.html": {Data: []byte("<html>console</html>")}}

	app, err := browsersession.NewApp(browsersession.Config{
		OIDC: oidcmw.BrowserConfig{
			Issuer:       idp.Issuer,
			ClientID:     "console",
			ClientSecret: "console-secret",
			RedirectURI:  "https://console.example/auth/callback",
			LoginPath:    "/auth/login",
			CookieSecure: true,
		},
		CookieEncryptionKey: strings.Repeat("0f", 32),
		PostLoginPath:       "/",
	}, api, staticFS)
	if err != nil {
		fmt.Println(err)
		return
	}

	mux := http.NewServeMux()
	mux.Handle("/auth/", http.StripPrefix("/auth", app.Auth))
	mux.Handle("/api/", http.StripPrefix("/api", app.API))
	mux.Handle("/", app.UI)

	do := func(method, target string, cookies []*http.Cookie) *httptest.ResponseRecorder {
		req := httptest.NewRequest(method, target, nil)
		for _, c := range cookies {
			req.AddCookie(c)
		}
		rr := httptest.NewRecorder()
		mux.ServeHTTP(rr, req)
		return rr
	}

	// Without a session the page redirects to login and the API says 401.
	fmt.Println("page:", do(http.MethodGet, "/", nil).Header().Get("Location"))
	fmt.Println("api:", do(http.MethodGet, "/api/me", nil).Code)

	// Login redirects to the provider and sets a state cookie.
	login := do(http.MethodGet, "/auth/login", nil)
	state := ""
	if u, err := url.Parse(login.Header().Get("Location")); err == nil {
		state = u.Query().Get("state")
	}

	// The provider sends the browser back with a code. The callback checks
	// the state, exchanges the code and sets the session cookies.
	callback := do(http.MethodGet, "/auth/callback?code=abc&state="+state, login.Result().Cookies())
	fmt.Println("callback:", callback.Code, callback.Header().Get("Location"))

	var session []*http.Cookie
	for _, c := range callback.Result().Cookies() {
		if c.MaxAge >= 0 {
			session = append(session, c)
		}
	}

	// With the session the page is served and the API sees a bearer token.
	fmt.Println("page:", do(http.MethodGet, "/", session).Body.String())
	fmt.Print("api: ", do(http.MethodGet, "/api/me", session).Body.String())

}
Output:
page: /auth/login
api: 401
callback: 302 /
page: <html>console</html>
api: bearer token present: true

type AuthHandler

type AuthHandler struct {
	// OIDCHandler starts the login flow and owns the state cookie.
	OIDCHandler *oidcmw.Handler
	// OIDCClient exchanges the authorization code and ends the provider
	// session on logout.
	OIDCClient *oidc.Client
	// RedirectURI is the callback URL registered with the provider.
	RedirectURI string
	// PostLoginPath is where the browser is sent after a successful login.
	PostLoginPath string
	// PostLogoutPath is where the browser is sent after logout.
	PostLogoutPath string
	// Cookies stores the session.
	Cookies *CookieSet
	// PublicConfig is the document served by GET /config.
	PublicConfig PublicConfig
}

AuthHandler serves the OIDC login flow of a browser session.

func (*AuthHandler) Handler

func (h *AuthHandler) Handler() http.Handler

Handler returns the routes of the login flow, relative to wherever the caller mounts them:

GET  /login     redirects to the provider (?prompt=create for sign-up)
GET  /callback  completes login and sets the session cookies
POST /logout    ends the session
GET  /config    returns PublicConfig

type Config

type Config struct {
	// OIDC is the identity provider, the client registered with it and the
	// cookie attributes. OIDC.LoginPath is the absolute path the browser is
	// sent to when it has no session; App.Auth must be mounted so that its
	// /login route is served there. OIDC.RedirectURI must reach App.Auth's
	// /callback route.
	OIDC oidcmw.BrowserConfig `mapstructure:"oidc"`

	// CookieEncryptionKey encrypts the session cookies. It is 64 hexadecimal
	// characters (an AES-256 key), for example from "openssl rand -hex 32".
	// Changing it ends every session.
	CookieEncryptionKey string `mapstructure:"cookie-encryption-key"`

	// PostLoginPath is where the browser is sent after login. Defaults to "/".
	PostLoginPath string `mapstructure:"post-login-path"`
	// PostLogoutPath is where the browser is sent after logout. Defaults to "/".
	PostLogoutPath string `mapstructure:"post-logout-path"`
}

Config configures a browser session app.

type CookieSet

type CookieSet struct {
	// Token configures the access-token cookie.
	Token oidcmw.CookieConfig
	// Refresh configures the refresh-token cookie.
	Refresh oidcmw.CookieConfig
	// Expiry configures the token-expiry cookie.
	Expiry oidcmw.CookieConfig
	// contains filtered or unexported fields
}

CookieSet reads and writes a Session as three encrypted cookies. Keeping them in one set applies the Secure, Domain and Path attributes consistently when setting and deleting them.

Example

ExampleCookieSet sets a session, reads it back from the request a browser would send, and clears it.

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"time"

	"github.com/dioad/auth/http/browsersession"
	oidcmw "github.com/dioad/auth/http/middleware/oidc"
)

func main() {
	// The key is 64 hexadecimal characters. Generate one with
	// "openssl rand -hex 32" and keep it out of source control.
	key := strings.Repeat("0f", 32)

	cookies, err := browsersession.NewCookieSet(key,
		oidcmw.CookieConfig{Name: "bff_session", Path: "/", Secure: true},
		oidcmw.CookieConfig{Name: "bff_refresh", Path: "/", Secure: true},
		oidcmw.CookieConfig{Name: "bff_expiry", Path: "/", Secure: true},
	)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Set: the response carries one encrypted cookie per part of the session.
	response := httptest.NewRecorder()
	err = cookies.Set(response, browsersession.Session{
		AccessToken:  "access-token",
		RefreshToken: "refresh-token",
		Expiry:       time.Date(2030, 1, 1, 12, 0, 0, 0, time.UTC),
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	request := httptest.NewRequest(http.MethodGet, "/", nil)
	for _, c := range response.Result().Cookies() {
		fmt.Println("set:", c.Name, "httponly:", c.HttpOnly, "plaintext:", strings.Contains(c.Value, "access-token"))
		request.AddCookie(c)
	}

	// Get: the server decrypts the cookies the browser sends back.
	session, err := cookies.Get(request)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("get:", session.AccessToken, session.RefreshToken, session.Expiry.Format(time.RFC3339))

	// Clear: every cookie is expired.
	cleared := httptest.NewRecorder()
	cookies.Clear(cleared)
	for _, c := range cleared.Result().Cookies() {
		fmt.Println("clear:", c.Name, "max-age:", c.MaxAge)
	}

}
Output:
set: bff_session httponly: true plaintext: false
set: bff_refresh httponly: true plaintext: false
set: bff_expiry httponly: true plaintext: false
get: access-token refresh-token 2030-01-01T12:00:00Z
clear: bff_session max-age: -1
clear: bff_refresh max-age: -1
clear: bff_expiry max-age: -1

func NewCookieSet

func NewCookieSet(encryptionKey string, token, refresh, expiry oidcmw.CookieConfig) (*CookieSet, error)

NewCookieSet returns a CookieSet that encrypts with encryptionKey, which is 64 hexadecimal characters (an AES-256 key). The three cookies must have distinct, non-empty names.

func (*CookieSet) Clear

func (s *CookieSet) Clear(w http.ResponseWriter)

Clear expires all three session cookies.

func (*CookieSet) Get

func (s *CookieSet) Get(r *http.Request) (Session, error)

Get decrypts the session carried by r. Only the access-token cookie is required: a missing or unreadable refresh-token or expiry cookie leaves that field of the Session zero.

func (*CookieSet) Present

func (s *CookieSet) Present(r *http.Request) bool

Present reports whether r carries a session cookie, without decrypting it.

func (*CookieSet) Set

func (s *CookieSet) Set(w http.ResponseWriter, session Session) error

Set encrypts session and writes it to w. The refresh and expiry cookies are only written when session has a refresh token and a known expiry.

type PublicConfig

type PublicConfig struct {
	Issuer   string `json:"issuer"`
	ClientID string `json:"client_id"`
}

PublicConfig is served by GET /config so the browser app can show which identity provider and client it signs in with. Neither value is secret.

type RefreshFunc

type RefreshFunc func(ctx context.Context, refreshToken string) (*oauth2.Token, error)

RefreshFunc exchanges a refresh token for a new token. oidc.Client's RefreshToken method is one, once its options are bound.

type Session

type Session struct {
	// AccessToken is the OAuth2 access token. It is always set.
	AccessToken string
	// RefreshToken is empty when the provider did not issue one, for example
	// without the offline_access scope. Such a session cannot be refreshed.
	RefreshToken string
	// Expiry is when AccessToken expires. It is zero when the provider did
	// not say, in which case the session is never refreshed proactively.
	Expiry time.Time
}

Session is the content of a browser session.

func (Session) ExpiresWithin

func (s Session) ExpiresWithin(window time.Duration, now time.Time) bool

ExpiresWithin reports whether the session can be refreshed and expires within window of now.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL