Quickstart: Go
This page gets a Go web application signing people in through your issuer
with go-oidc and
golang.org/x/oauth2:
authorization code with PKCE, an in-memory session, a refresh through
TokenSource, and sign-out. It applies
Sign users in with OpenID Connect and uses
only the standard library’s HTTP server. It takes about ten minutes.
Before you begin
Section titled “Before you begin”- Go 1.22 or later. The routes use method patterns such as
GET /login. - A confidential client on your issuer with
client_secret_basic, the redirect URIhttp://localhost:8080/callback, the post-logout redirect URIhttp://localhost:8080/, and a minted secret. See Register a client.
Create the module
Section titled “Create the module”mkdir authwise-go && cd authwise-gogo mod init example.com/authwise-quickstartgo get github.com/coreos/go-oidc/v3/oidc golang.org/x/oauth2This page was verified with go-oidc v3.21 and x/oauth2 v0.37.
Write the server
Section titled “Write the server”Create main.go:
// Authwise quickstart: OpenID Connect sign-in with go-oidc and x/oauth2.package main
import ( "context" "crypto/rand" "encoding/hex" "fmt" "html" "log" "net/http" "net/url" "os" "sync" "time"
"github.com/coreos/go-oidc/v3/oidc" "golang.org/x/oauth2")
const appURL = "http://localhost:8080"
type login struct{ nonce, verifier string }type session struct { sub, idToken string token *oauth2.Token}
var ( mu sync.Mutex logins = map[string]login{} // keyed by state sessions = map[string]*session{} // keyed by the session cookie)
func random() string { b := make([]byte, 16); rand.Read(b); return hex.EncodeToString(b) }
func main() { issuer := os.Getenv("AUTHWISE_ISSUER") provider, err := oidc.NewProvider(context.Background(), issuer) if err != nil { log.Fatal(err) } var disc struct { EndSessionEndpoint string `json:"end_session_endpoint"` } if err := provider.Claims(&disc); err != nil { log.Fatal(err) } cfg := oauth2.Config{ ClientID: os.Getenv("AUTHWISE_CLIENT_ID"), ClientSecret: os.Getenv("AUTHWISE_CLIENT_SECRET"), Endpoint: provider.Endpoint(), RedirectURL: appURL + "/callback", Scopes: []string{oidc.ScopeOpenID, "profile", "email", oidc.ScopeOfflineAccess}, } verifier := provider.Verifier(&oidc.Config{ClientID: cfg.ClientID})
current := func(r *http.Request) (string, *session) { c, err := r.Cookie("session") if err != nil { return "", nil } mu.Lock() defer mu.Unlock() return c.Value, sessions[c.Value] }
http.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { if _, s := current(r); s != nil { fmt.Fprintf(w, `Signed in as %s (access token expires %s). <a href="/refresh">Refresh</a> <a href="/logout">Sign out</a>`, html.EscapeString(s.sub), s.token.Expiry.Format(time.RFC3339)) return } fmt.Fprint(w, `Signed out. <a href="/login">Sign in</a>`) })
http.HandleFunc("GET /login", func(w http.ResponseWriter, r *http.Request) { state, nonce, pkce := random(), random(), oauth2.GenerateVerifier() mu.Lock() logins[state] = login{nonce, pkce} mu.Unlock() http.SetCookie(w, &http.Cookie{Name: "login", Value: state, Path: "/", HttpOnly: true, MaxAge: 300}) http.Redirect(w, r, cfg.AuthCodeURL(state, oidc.Nonce(nonce), oauth2.S256ChallengeOption(pkce)), http.StatusFound) })
http.HandleFunc("GET /callback", func(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() c, err := r.Cookie("login") mu.Lock() l, ok := logins[q.Get("state")] delete(logins, q.Get("state")) mu.Unlock() if err != nil || !ok || c.Value != q.Get("state") || q.Get("iss") != issuer { http.Error(w, "state mismatch", http.StatusBadRequest) return } tok, err := cfg.Exchange(r.Context(), q.Get("code"), oauth2.VerifierOption(l.verifier)) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } raw, _ := tok.Extra("id_token").(string) idt, err := verifier.Verify(r.Context(), raw) if err != nil || idt.Nonce != l.nonce { http.Error(w, "invalid id_token", http.StatusUnauthorized) return } id := random() mu.Lock() sessions[id] = &session{sub: idt.Subject, idToken: raw, token: tok} mu.Unlock() http.SetCookie(w, &http.Cookie{Name: "session", Value: id, Path: "/", HttpOnly: true}) http.Redirect(w, r, "/", http.StatusFound) })
http.HandleFunc("GET /refresh", func(w http.ResponseWriter, r *http.Request) { _, s := current(r) if s == nil { http.Redirect(w, r, "/login", http.StatusFound) return } s.token.Expiry = time.Now().Add(-time.Second) // expired → TokenSource uses the refresh token tok, err := cfg.TokenSource(r.Context(), s.token).Token() if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } s.token = tok // keeps the rotated refresh token fmt.Fprintf(w, `Refreshed; access token now expires %s. <a href="/">Home</a>`, tok.Expiry.Format(time.RFC3339)) })
http.HandleFunc("GET /logout", func(w http.ResponseWriter, r *http.Request) { id, s := current(r) mu.Lock() delete(sessions, id) mu.Unlock() http.SetCookie(w, &http.Cookie{Name: "session", Path: "/", MaxAge: -1}) if s == nil { http.Redirect(w, r, "/", http.StatusFound) return } end := disc.EndSessionEndpoint + "?" + url.Values{"id_token_hint": {s.idToken}, "post_logout_redirect_uri": {appURL + "/"}}.Encode() http.Redirect(w, r, end, http.StatusFound) })
log.Println("listening on", appURL) log.Fatal(http.ListenAndServe(":8080", nil))}What each handler does:
/logincreatesstate,nonce, and the PKCE verifier, keeps them keyed bystate, bindsstateto the browser with a short-lived cookie, and redirects withoidc.Nonceandoauth2.S256ChallengeOption./callbackchecks that the cookie, the storedstate, and the callback’sissall match, exchanges the code withoauth2.VerifierOption, verifies the ID token with the provider’s verifier, and compares the nonce.idt.Subjectis the person’s stable ID./refreshforces the token’s expiry into the past and asks theTokenSourcefor a token, which performs the refresh grant. The returned token carries the new refresh token, so the session stores it./logoutdrops the session and sends the browser to the issuer’s end-session endpoint, read from the discovery document, which ends the issuer session and returns to/.
Run it
Section titled “Run it”export AUTHWISE_ISSUER=https://login.example.comexport AUTHWISE_CLIENT_ID=CLIENT_IDexport AUTHWISE_CLIENT_SECRET="$(cat client-secret.txt)"go run .Replace https://login.example.com with your issuer’s URL and CLIENT_ID
with the client’s ID. Open http://localhost:8080/, click Sign in, and
sign in on the hosted page. The home page shows Signed in as u-… with
the access token’s expiry. Refresh shows a later expiry, and Sign
out returns you to the signed-out page.
Good to know
Section titled “Good to know”- PKCE is two options:
S256ChallengeOptionon the authorization URL andVerifierOptiononExchange. - The verifier checks the signature,
iss,aud, andexp. It does not check the nonce. CompareidToken.Noncewith the value you stored. - The ID token arrives in
tok.Extra("id_token"). Keep the raw string forid_token_hintat sign-out. TokenSourcerefreshes only whenExpiryis within 10 seconds or in the past, and never whenExpiryis zero. Always store the token theTokenSourcereturns, because the refresh token rotates.go-oidchas no field for the end-session endpoint. Read it from the discovery document withprovider.Claims.- The in-memory maps and the cookies without
Secureare localhost shortcuts. A real application keeps sessions in a store and setsSecureandSameSiteon its cookies.
What’s next
Section titled “What’s next”- Send
tok.AccessTokenas a bearer token to the API the client’s audience names.go-oidccan validate it there with the same provider. - Read Keep the session alive for the refresh token lifetimes and how to tune them.