Skip to main content

Sign-in for a Go web app

Add sign-in to a net/http app with a cookie session, and protect handlers with middleware.

RecipeDraftView source
This page is a draft. The code exists, and not all of it has been run for this page yet. The page says what was checked.
Works with
GoGo net/http

What it shows​

  1. NewWebAuth() gives a router with the routes /auth/login, /auth/callback and /auth/logout.
  2. /auth/login goes to the hosted sign-in page. The callback exchanges the code and stores the tokens and the profile in a signed cookie.
  3. Middleware reads the session, and handlers read the person with UserFromContext().
  4. RequireAuthRedirect() sends a signed-out visitor of a page to sign-in. RequireAuth answers 401 on an API route.
  5. The route /signout of the app ends the session of the app and the session at LumoAuth. A small guard keeps other sites from signing the person out.

Before you start​

  • Go 1.22 or later.
  • An API key with the scopes admin:clients:read and admin:clients:write. Create it in the portal under Applications & developer tools, API keys.
  • A confidential application with the redirect URI http://localhost:3000/auth/callback. The setup script creates it.
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
LUMOAUTH_API_KEYAn API key with the scopes admin:clients:read and admin:clients:write. Only the setup script uses it.
APP_URLOptional. The address of your app, when it is not http://localhost:3000. The setup script and the app read it.
LUMOAUTH_CLIENT_IDThe client ID of the application. The setup script prints it.
LUMOAUTH_CLIENT_SECRETThe client secret of the application. The setup script prints it.
SESSION_SECRETAt least 32 random bytes. The SDK signs the session cookie with this value. The setup script prints a random value.

The setup script creates the application through the Admin API and prints the variables of the app. LumoAuth shows a client secret only once, so each run makes a new secret.

node sign-in/go/setup.mjs
setup.mjs
// Creates the application that the Go app signs in with: a confidential
// application with the callback address of the app. Run it again at any time.
//
// node sign-in/go/setup.mjs
//
// The API key needs the scopes admin:clients:read and admin:clients:write.
// APP_URL is the address of your app. The default is http://localhost:3000.
import { randomBytes } from 'node:crypto';
import { call, list, printEnv } from '../../_lib/admin.mjs';

const appUrl = (process.env.APP_URL ?? 'http://localhost:3000').replace(/\/+$/, '');
const name = 'Go sign-in';
const redirectUris = [`${appUrl}/auth/callback`];

let secret;
let client = (await list('/admin/clients')).find((c) => c.name === name);
if (client) {
// LumoAuth shows a client secret only once, so a second run makes a new one.
await call('PATCH', `/admin/clients/${client.id}`, { redirectUris });
secret = (await call('POST', `/admin/clients/${client.id}/rotate-secret`)).data.secret;
} else {
client = (await call('POST', '/admin/clients', { name, redirectUris, isConfidential: true })).data;
secret = client.secret;
}

console.log(`Application "${name}" is ready. Its redirect URI is ${redirectUris[0]}.`);
printEnv({
LUMOAUTH_CLIENT_ID: client.clientId,
LUMOAUTH_CLIENT_SECRET: secret,
// The SDK signs the session cookie with this value.
SESSION_SECRET: randomBytes(32).toString('hex'),
});

Copy the export lines that the script prints into the terminal where you start the app.

Sign-out returns to your app only when the address is registered. The Admin API has no field for it, so add it in the portal:

  1. Open Applications and select Go sign-in.
  2. Open the Configuration tab and go to the section Logout.
  3. Under Post-logout redirect URIs, enter http://localhost:3000/.
  4. Select Save configuration.

Code​

Run each command from the recipes folder of the examples repository. Set the folder up once for your language. The signed-out answers below were seen. With Scope: "openid" in WebConfig, the whole flow ran in a browser, and the profile then has no email address and no name. In that run, a link and a form on another site did not sign the person out.

sign-in/go/go/main.go
// A net/http app with sign-in: the hosted sign-in page, a cookie session, a
// protected page, a protected API route and sign-out.
//
// go run ./sign-in/go/go
package main

import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"strings"

lumoauth "github.com/lumoauth/lumo-auth-go"
)

const sessionCookie = "lumo_session"

func main() {
appURL := strings.TrimRight(os.Getenv("APP_URL"), "/")
if appURL == "" {
appURL = "http://localhost:3000"
}
address, err := url.Parse(appURL)
if err != nil {
log.Fatal(err)
}

// The address of LumoAuth and the organization come from LUMOAUTH_URL and
// LUMOAUTH_ORG_ID.
auth, err := lumoauth.NewWebAuth(lumoauth.WebConfig{
ClientID: os.Getenv("LUMOAUTH_CLIENT_ID"),
ClientSecret: os.Getenv("LUMOAUTH_CLIENT_SECRET"),
SessionSecret: os.Getenv("SESSION_SECRET"),
CallbackPath: "/auth/callback",
CookieName: sessionCookie,
// A browser sends a Secure cookie only over HTTPS.
CookieSecure: lumoauth.Bool(address.Scheme == "https"),
})
if err != nil {
log.Fatal(err)
}

mux := http.NewServeMux()

// Another site must not be able to sign a person out. This guard covers
// /signout and /auth/logout of the router. A GET signs out at once only
// when the browser says that it comes from this app or from a typed
// address. Any other GET gets a page with a button, and a POST must come
// from this app.
signOutGuard := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
site, origin := req.Header.Get("Sec-Fetch-Site"), req.Header.Get("Origin")
fromThisApp := origin == address.Scheme+"://"+address.Host || ((origin == "" || origin == "null") && site == "same-origin")
if req.Method == http.MethodPost && !fromThisApp {
http.Error(rw, "Sign-out refused: the request did not come from this app.", http.StatusForbidden)
return
}
if req.Method != http.MethodPost && site != "same-origin" && site != "none" {
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
rw.Header().Set("Cache-Control", "no-store")
rw.Header().Set("X-Content-Type-Options", "nosniff")
rw.Header().Set("X-Frame-Options", "DENY")
rw.Header().Set("Referrer-Policy", "same-origin")
// No form-action: Chromium applies it to the redirect to LumoAuth too.
rw.Header().Set("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'")
fmt.Fprint(rw, `<p>Do you want to sign out?</p><form method="post"><button>Sign out</button></form>`)
return
}
next.ServeHTTP(rw, req)
})
}

// Adds /auth/login, /auth/callback and /auth/logout.
mux.Handle("/auth/", auth.Router())
mux.Handle("/auth/logout", signOutGuard(auth.Router()))

// A public page. UserFromContext returns nil when nobody is signed in.
mux.HandleFunc("/{$}", func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
user := lumoauth.UserFromContext(req.Context())
if user == nil {
fmt.Fprint(rw, `<p>Nobody is signed in.</p><a href="/auth/login">Sign in</a>`)
return
}
fmt.Fprintf(rw, `<p>Signed in as %s.</p><p><a href="/dashboard">Dashboard</a> · <a href="/api/me">Profile as JSON</a> · <a href="/signout">Sign out</a></p>`, user.Email)
})

// A protected page: RequireAuthRedirect sends a signed-out visitor to
// sign-in and brings the person back here.
dashboard := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
user := lumoauth.UserFromContext(req.Context())
fmt.Fprintf(rw, `<h1>Dashboard</h1><p>User ID: %s</p><a href="/">Home</a>`, user.Sub)
})
mux.Handle("/dashboard", auth.RequireAuthRedirect("/auth/login")(dashboard))

// A protected API route: RequireAuth answers 401 without a session.
me := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
user := lumoauth.UserFromContext(req.Context())
rw.Header().Set("Content-Type", "application/json")
json.NewEncoder(rw).Encode(map[string]string{"sub": user.Sub, "email": user.Email, "name": user.Name})
})
mux.Handle("/api/me", auth.RequireAuth(me))

// /auth/logout of the router ends only the session of this app. This route
// also ends the session at LumoAuth: it sends the browser to the logout
// endpoint with the ID token, and LumoAuth sends it back to the home page.
mux.Handle("/signout", signOutGuard(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
tokens := lumoauth.TokensFromContext(req.Context())
if tokens == nil {
http.Redirect(rw, req, "/", http.StatusFound)
return
}
// What /auth/logout does: revoke the refresh token, expire the cookie.
_ = auth.Client().Auth.Revoke(req.Context(), lumoauth.RevokeParams{
Token: tokens.RefreshToken,
TokenTypeHint: "refresh_token",
ClientID: os.Getenv("LUMOAUTH_CLIENT_ID"),
ClientSecret: os.Getenv("LUMOAUTH_CLIENT_SECRET"),
})
http.SetCookie(rw, &http.Cookie{Name: sessionCookie, Path: "/", MaxAge: -1})

logout, err := auth.Client().OrgPath("/oauth/logout")
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
query := url.Values{"id_token_hint": {tokens.IDToken}, "post_logout_redirect_uri": {appURL + "/"}}
http.Redirect(rw, req, auth.Client().BaseURL()+logout+"?"+query.Encode(), http.StatusFound)
})))

// Middleware reads the session and puts the person on the context of
// every request. It does not refuse anybody.
log.Printf("Listening on %s", appURL)
log.Fatal(http.ListenAndServe(address.Host, auth.Middleware(mux)))
}
go run ./sign-in/go/go

Compiles. Not run against an organization. The app ran, and sign-in stopped at the callback with securecookie: the value is too long: with the default scopes, the session of the SDK is longer than its cookie can hold.

Check the result​

Open http://localhost:3000 in a browser, select Sign in, and sign in as a user of your organization.

Output
Signed out
GET / 200 Nobody is signed in.
GET /dashboard 302 /auth/login?return_to=%2Fdashboard
GET /api/me 401 unauthenticated

Signed in
GET / 200 Signed in as maya.chen@example.com.
GET /dashboard 200 User ID: 0195c1e2-7a41-7c3e-9b1d-2f6a8d4e5c10
GET /api/me 200 {"email":"maya.chen@example.com","name":"Maya Chen","sub":"0195c1e2-7a41-7c3e-9b1d-2f6a8d4e5c10"}
  • The browser holds the cookie lumo_session, marked httpOnly. Local storage and session storage hold no token.
  • Sign out returns to /, and the next visit to /dashboard shows the sign-in page again.
  • A link to /signout on another site shows a page with the question "Do you want to sign out?". The person stays signed in until they select Sign out. A form on another site that posts to the route gets 403. The guard of the recipe covers /signout and /auth/logout.

Limits​

  • The SDK keeps the whole session in the cookie: the profile, the access token, the refresh token and the ID token. The cookie is signed, not encrypted, and it holds at most 4,096 characters. With the scopes openid profile email the session was longer in the test, and the callback answered could not save the session. With Scope: "openid" it fitted, and the profile then has only the user ID.
  • /auth/logout of the router revokes the refresh token and removes the cookie. The person stays signed in at LumoAuth, and the next /auth/login returns without a sign-in page. The route /signout of this recipe therefore calls the logout endpoint itself.
  • Middleware does not refresh the access token. Call RefreshSession() in a handler that needs a current token.
  • RequireAuth and RequireAuthRedirect() check that a session exists. They do not check roles or permissions.