Add Keycloak login to a Go app
Sign users in to a Go web app with Keycloak using go-oidc and x/oauth2, verify access tokens in API middleware, and log users out.
This guide signs users in to a Go web app with go-oidc and golang.org/x/oauth2, protects an API route with Keycloak access tokens, and logs users out of Keycloak.
Written against github.com/coreos/go-oidc/v3 v3.21.0 and golang.org/x/oauth2 v0.38.0 on Go 1.27 and Keycloak 26.8, checked on 25 November 2026. The sample needs Go 1.24 or newer (crypto/rand.Text and method patterns in http.ServeMux).
Replace auth.example.com with your RealmDeploy hostname and acme with your realm.
Create the client in Keycloak
In your realm, open Clients and choose Create client. Use these values, then choose Save:
| Setting | Value |
|---|---|
| Client type | OpenID Connect |
| Client ID | my-app |
| Client authentication | On |
| Authentication flow | Standard flow only. Turn Direct access grants off. |
| Root URL | http://localhost:8080 |
| Valid redirect URIs | http://localhost:8080/callback |
| Valid post logout redirect URIs | http://localhost:8080/ |
| Web origins | Leave empty. The browser never calls Keycloak from JavaScript in this app. |
Copy the Client secret from the client's Credentials tab.
Go's net/http has no default port; the sample listens on 8080. For production, add the same paths on your app's HTTPS address, for example https://app.example.com/callback and https://app.example.com/, and set APP_URL to match. Keycloak compares redirect URIs exactly.
Environment variables
OIDC_ISSUER=https://auth.example.com/realms/acme
OIDC_CLIENT_ID=my-app
OIDC_CLIENT_SECRET=paste-the-client-secret
API_AUDIENCE=my-api
APP_URL=http://localhost:8080Go does not read .env files. Load the file into your shell before you run the app: set -a; . ./.env; set +a.
Install
go mod init example.com/app
go get github.com/coreos/go-oidc/[email protected] golang.org/x/[email protected]Add login
package main
import (
"context"
"crypto/rand"
"encoding/json"
"log"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/coreos/go-oidc/v3/oidc"
"golang.org/x/oauth2"
)
var (
appURL = os.Getenv("APP_URL") // http://localhost:8080
secure = strings.HasPrefix(appURL, "https://")
provider *oidc.Provider
oauthConfig oauth2.Config
idVerifier *oidc.IDTokenVerifier
apiVerifier *oidc.IDTokenVerifier
endSession string
)
func main() {
ctx := context.Background()
// Reads https://auth.example.com/realms/acme/.well-known/openid-configuration
var err error
provider, err = oidc.NewProvider(ctx, os.Getenv("OIDC_ISSUER"))
if err != nil {
log.Fatal(err)
}
// go-oidc has no field for the logout endpoint; read it from discovery.
var meta struct {
EndSessionEndpoint string `json:"end_session_endpoint"`
}
if err := provider.Claims(&meta); err != nil {
log.Fatal(err)
}
endSession = meta.EndSessionEndpoint
oauthConfig = oauth2.Config{
ClientID: os.Getenv("OIDC_CLIENT_ID"),
ClientSecret: os.Getenv("OIDC_CLIENT_SECRET"),
RedirectURL: appURL + "/callback",
Endpoint: provider.Endpoint(),
Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
}
// ID tokens: aud must contain this app's client ID.
idVerifier = provider.Verifier(&oidc.Config{
ClientID: oauthConfig.ClientID,
SupportedSigningAlgs: []string{oidc.RS256},
})
// Access tokens sent to the API: aud must contain the API audience.
apiVerifier = provider.Verifier(&oidc.Config{
ClientID: os.Getenv("API_AUDIENCE"),
SupportedSigningAlgs: []string{oidc.RS256},
})
mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", home)
mux.HandleFunc("GET /login", login)
mux.HandleFunc("GET /callback", callback)
mux.HandleFunc("GET /logout", logout)
mux.Handle("GET /api/me", requireToken(apiVerifier, http.HandlerFunc(apiMe)))
log.Println("listening on", appURL)
log.Fatal(http.ListenAndServe(":8080", mux))
}
func home(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`<a href="/login">Log in</a> | <a href="/logout">Log out</a>`))
}
func setTempCookie(w http.ResponseWriter, name, value string) {
http.SetCookie(w, &http.Cookie{
Name: name, Value: value, Path: "/", MaxAge: int((10 * time.Minute).Seconds()),
HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode,
})
}
func login(w http.ResponseWriter, r *http.Request) {
state, nonce := rand.Text(), rand.Text()
setTempCookie(w, "state", state)
setTempCookie(w, "nonce", nonce)
http.Redirect(w, r, oauthConfig.AuthCodeURL(state, oidc.Nonce(nonce)), http.StatusFound)
}
func callback(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
if e := q.Get("error"); e != "" {
http.Error(w, e+": "+q.Get("error_description"), http.StatusBadRequest)
return
}
state, err := r.Cookie("state")
if err != nil || q.Get("state") != state.Value {
http.Error(w, "state does not match", http.StatusBadRequest)
return
}
token, err := oauthConfig.Exchange(r.Context(), q.Get("code"))
if err != nil {
http.Error(w, "code exchange failed: "+err.Error(), http.StatusInternalServerError)
return
}
rawIDToken, ok := token.Extra("id_token").(string)
if !ok {
http.Error(w, "no id_token in token response", http.StatusInternalServerError)
return
}
idToken, err := idVerifier.Verify(r.Context(), rawIDToken)
if err != nil {
http.Error(w, "invalid ID token: "+err.Error(), http.StatusInternalServerError)
return
}
nonce, err := r.Cookie("nonce")
if err != nil || idToken.Nonce != nonce.Value {
http.Error(w, "nonce does not match", http.StatusBadRequest)
return
}
var claims struct {
Sub string `json:"sub"`
PreferredUsername string `json:"preferred_username"`
Email string `json:"email"`
}
if err := idToken.Claims(&claims); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Keep the ID token for logout. Use your own session store in a real app.
http.SetCookie(w, &http.Cookie{
Name: "id_token", Value: rawIDToken, Path: "/",
HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode,
})
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(claims)
}Run go run ., open http://localhost:8080 and choose Log in. After Keycloak, the callback shows the user's claims as JSON.
What each step does:
oidc.NewProviderreads the discovery document and checks that itsissueris exactlyOIDC_ISSUER.provider.Endpoint()givesoauth2.Configthe authorization and token endpoints./loginstores a randomstateandnoncein short-lived HttpOnly cookies.SameSite=Laxlets them come back on Keycloak's redirect./callbackcomparesstate, callsExchangewith the code, takesid_tokenfrom the token response and verifies it: signature against the realm's JWKS, issuer, expiry, andaudcontainingmy-app. Then it compares the nonce.
Keycloak signs tokens with RS256 by default. SupportedSigningAlgs pins that, because the realm's discovery document lists many algorithms. If you change the realm's default signature algorithm, change it here too.
The sample keeps no session of its own, to stay short. Put the user and the ID token in your session store instead of a cookie.
Protect an API
Add an Audience mapper
go-oidc's verifier was written for ID tokens: it requires aud to contain oidc.Config.ClientID. Keycloak access tokens carry aud: account by default, and only when the user has roles of the account client. So give access tokens your API's audience, and use that as the verifier's ClientID. Add the mapper to the client that calls the API, here my-app:
- Open Clients, then
my-app, then the Client scopes tab, thenmy-app-dedicated. - Choose Configure a new mapper, then Audience. If the scope already has mappers, choose Add mapper, By configuration, Audience.
- Set Name to
my-api audience, Included Custom Audience tomy-api, Add to access token on and Add to ID token off. Choose Save.
If your API has its own client in Keycloak, choose it under Included Client Audience instead, and set API_AUDIENCE to its client ID.
To check, open the client's Client scopes tab, then the Evaluate sub-tab, pick a user and look at Generated access token: aud should contain my-api.
Leave Add to ID token off: then an ID token, whose aud is my-app, is not accepted by the API.
Verify the token in middleware
Add this to main.go:
type claimsKey struct{}
// requireToken accepts a request only with a valid Keycloak access token.
func requireToken(v *oidc.IDTokenVerifier, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok || raw == "" {
w.Header().Set("WWW-Authenticate", "Bearer")
http.Error(w, "missing bearer token", http.StatusUnauthorized)
return
}
// Checks signature (JWKS), issuer, expiry and that aud contains the API audience.
token, err := v.Verify(r.Context(), raw)
if err != nil {
w.Header().Set("WWW-Authenticate", `Bearer error="invalid_token"`)
http.Error(w, "invalid token: "+err.Error(), http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), claimsKey{}, token)))
})
}
func apiMe(w http.ResponseWriter, r *http.Request) {
token := r.Context().Value(claimsKey{}).(*oidc.IDToken)
var claims struct {
PreferredUsername string `json:"preferred_username"`
}
token.Claims(&claims)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"sub": token.Subject, "username": claims.PreferredUsername})
}The verifier caches the realm's keys and fetches them again when a token has a key ID it does not know, so key rotation needs no restart. A caller sends a user's access token issued to my-app:
curl -i -H "Authorization: Bearer $ACCESS_TOKEN" http://localhost:8080/api/meIf you cannot add an Audience mapper, or need to accept several audiences, turn go-oidc's check off and check aud yourself. Never set SkipClientIDCheck without your own check:
verifier := provider.Verifier(&oidc.Config{
SkipClientIDCheck: true, // we check aud below
SupportedSigningAlgs: []string{oidc.RS256},
})
token, err := verifier.Verify(ctx, raw)
if err != nil {
return nil, err
}
if !slices.Contains(token.Audience, "my-api") {
return nil, errors.New("token is not meant for this API")
}Log out
Deleting your cookie or session ends only your app's login. The Keycloak session stays, so the next Log in signs the user straight back in. Send the browser to the end_session_endpoint read from discovery in main:
func logout(w http.ResponseWriter, r *http.Request) {
params := url.Values{
"client_id": {oauthConfig.ClientID},
"post_logout_redirect_uri": {appURL + "/"},
}
if c, err := r.Cookie("id_token"); err == nil {
params.Set("id_token_hint", c.Value)
}
http.SetCookie(w, &http.Cookie{Name: "id_token", Path: "/", MaxAge: -1})
http.Redirect(w, r, endSession+"?"+params.Encode(), http.StatusFound)
}The redirect looks like https://auth.example.com/realms/acme/protocol/openid-connect/logout?client_id=my-app&id_token_hint=...&post_logout_redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F. Keycloak ends its session and returns the browser to http://localhost:8080/, which must be listed in Valid post logout redirect URIs. With id_token_hint, Keycloak does not ask the user to confirm. The logout URL builder builds and checks the same URL.
Common errors
| Error | Cause | Fix |
|---|---|---|
oidc: issuer URL provided to client (...) did not match the issuer URL returned by provider (...) | OIDC_ISSUER differs from the discovery document's issuer, often by a trailing slash or another hostname. | Use https://auth.example.com/realms/acme exactly. Check it with the OIDC discovery viewer. |
| Keycloak shows Invalid parameter: redirect_uri | APP_URL + "/callback" is not in Valid redirect URIs. | Make both identical. Compare them with the redirect URI matcher. |
state does not match | The state cookie did not come back, usually because the app was opened on another host name than APP_URL (127.0.0.1 against localhost). | Open the app on the APP_URL host. |
code exchange failed: oauth2: "unauthorized_client" ... | OIDC_CLIENT_SECRET does not match the client's secret. | Copy the secret again from the Credentials tab. Look up other error codes with the OAuth error lookup. |
code exchange failed: oauth2: "invalid_grant" ... | The code was already used or expired, for example after reloading the callback page. | Start again from /login. |
| Keycloak shows Invalid redirect uri after logout | post_logout_redirect_uri is not in Valid post logout redirect URIs. | Add http://localhost:8080/ (or your production URL) exactly. |
401 invalid token: oidc: expected audience "my-api" got ["account"] | The access token has no my-api in aud. | Add the Audience mapper. Check the token with the JWT decoder. |
401 invalid token: oidc: token is expired | Keycloak access tokens live 5 minutes by default. | The caller refreshes the token and retries. |
401 invalid token: oidc: id token issued by a different provider | The token comes from another realm or hostname. | Request the token from the realm in OIDC_ISSUER. |
FAQ
Why does go-oidc talk about ID tokens when I verify access tokens?
IDTokenVerifier verifies any JWT with iss, aud and exp, and Keycloak access tokens are such JWTs. The names come from go-oidc's main use. With the Audience mapper, ClientID in oidc.Config is the audience your API expects.
Should I use PKCE as well?
You can. golang.org/x/oauth2 has GenerateVerifier, S256ChallengeOption for AuthCodeURL and VerifierOption for Exchange. Store the verifier next to the state.
Can the API check roles?
Yes. Read Keycloak's realm_access.roles or resource_access.<client>.roles claims with token.Claims. The Keycloak token roles tool shows where roles land in a token.
Do I need to ask you to open an outgoing connection?
No. Every call in this guide goes from your app to Keycloak: discovery, token and JWKS. Logout is a browser redirect, so Keycloak never calls your app.
Sources
Add Keycloak login to a FastAPI app
Validate Keycloak access tokens in FastAPI with PyJWT and JWKS, add browser login with Authlib, and log users out of Keycloak.
Add Keycloak login to a Laravel app
Sign users in to a Laravel 13 app with Keycloak through Socialite and the SocialiteProviders driver, protect API routes with firebase/php-jwt, and log out.