Skip to content

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.

  • 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 URI http://localhost:8080/callback, the post-logout redirect URI http://localhost:8080/, and a minted secret. See Register a client.
Terminal window
mkdir authwise-go && cd authwise-go
go mod init example.com/authwise-quickstart
go get github.com/coreos/go-oidc/v3/oidc golang.org/x/oauth2

This page was verified with go-oidc v3.21 and x/oauth2 v0.37.

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:

  • /login creates state, nonce, and the PKCE verifier, keeps them keyed by state, binds state to the browser with a short-lived cookie, and redirects with oidc.Nonce and oauth2.S256ChallengeOption.
  • /callback checks that the cookie, the stored state, and the callback’s iss all match, exchanges the code with oauth2.VerifierOption, verifies the ID token with the provider’s verifier, and compares the nonce. idt.Subject is the person’s stable ID.
  • /refresh forces the token’s expiry into the past and asks the TokenSource for a token, which performs the refresh grant. The returned token carries the new refresh token, so the session stores it.
  • /logout drops 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 /.
Terminal window
export AUTHWISE_ISSUER=https://login.example.com
export AUTHWISE_CLIENT_ID=CLIENT_ID
export 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.

  • PKCE is two options: S256ChallengeOption on the authorization URL and VerifierOption on Exchange.
  • The verifier checks the signature, iss, aud, and exp. It does not check the nonce. Compare idToken.Nonce with the value you stored.
  • The ID token arrives in tok.Extra("id_token"). Keep the raw string for id_token_hint at sign-out.
  • TokenSource refreshes only when Expiry is within 10 seconds or in the past, and never when Expiry is zero. Always store the token the TokenSource returns, because the refresh token rotates.
  • go-oidc has no field for the end-session endpoint. Read it from the discovery document with provider.Claims.
  • The in-memory maps and the cookies without Secure are localhost shortcuts. A real application keeps sessions in a store and sets Secure and SameSite on its cookies.
  • Send tok.AccessToken as a bearer token to the API the client’s audience names. go-oidc can validate it there with the same provider.
  • Read Keep the session alive for the refresh token lifetimes and how to tune them.