At a long stone counter by lantern light, the Ghost, a stone android stooping behind it, hands the Gopher a plain brass tag on a cord with one hand while with the other it turns a brass key in the one open compartment of a tall wall of small sealed compartments.

Production

OAuth and OpenID Connect for an agent service in Go: sign-in, sessions, and each user’s own credentials

Sign people in, keep their tokens off the browser, and call other services with each user’s own credentials.

Updated Advanced

On the agent compass Stage 3 of 4 · Run the tools

An agent that people use from a browser has three jobs that OAuth and OpenID Connect split between them. It has to know who is asking, which is signing in. It has to keep knowing it on every request after, which is the session. And it has to act at other services for that person, reading their calendar or filing issues in their tracker, with their rights and nobody else’s, which is their connected accounts.

OpenID Connect handles the first; OAuth handles the third. Each job has its own token, meant for a different party, and most mistakes in this area come from using one where another belongs. This page builds the service in Go and runs it offline, against an identity provider and a calendar service, with tests for each check. MCP authorization covers the other end: the server that receives a token and decides whether to accept it.

Four credentials, four audiences

  • The ID token is for the agent service. Its audience is the service’s client ID, and it says who signed in, once. It is never sent to an API.
  • An access token is for one API. The calendar’s is issued for the calendar, by the calendar’s authorization server, and the agent’s tools send it there and nowhere else.
  • A refresh token is for the authorization server that issued it. It renews access tokens while the user is away, for as long as the connection lasts, which makes it the credential most worth stealing.
  • The session cookie is for the browser. It holds a random ID and nothing else, and the service looks everything up from it.

The browser holds only the last. The other three stay on the server.

The whole thing, in one run

The demo starts an identity provider that people sign in with, a calendar API with its own authorization server, and the agent service, all on loopback addresses, with stand-ins for two people’s browsers. It prints every request and never a token:

go run ./cmd/agentweb (in code/mcpauth)
In the log: agent is the agent service, idp the identity provider
users sign in with, cal-auth the calendar's authorization server,
and calendar its API. Lines starting "agent ->" are requests the
agent service makes; the rest are the browsers'.

0. The agent service starts and reads the identity provider's metadata
   agent ->     GET  idp      /.well-known/openid-configuration  -> 200

1. Alice opens the agent service and signs in
   alice        GET  agent    /  -> 302 to /login
   alice        GET  agent    /login  -> 302 to idp/authorize
   alice        GET  idp      /authorize  scope="email openid" S256, state, nonce  -> 302 to agent/callback
   agent ->     POST idp      /token  authorization_code  -> 200
   agent ->     GET  idp      /jwks  -> 200
   alice        GET  agent    /callback  code, state, iss=idp  -> 200
   alice        GET  agent    /  -> 200
   page: signed in as alice@example.com

2. She asks for her next meeting
   alice        POST agent    /ask  -> 200
   reply: I can't reach that account (calendar: not connected). Connect it, then ask again.

3. She connects her calendar
   alice        POST agent    /connect/calendar  -> 303 to cal-auth/authorize
   alice        GET  cal-auth /authorize  scope="calendar:read offline_access" resource=calendar S256, state  -> 302 to agent/connect/calendar/callback
   agent ->     POST cal-auth /token  authorization_code  -> 200
   alice        GET  agent    /connect/calendar/callback  code, state, iss=cal-auth  -> 200
   page: connected calendar

4. She asks again
   agent ->     GET  calendar /events  -> 200
   alice        POST agent    /ask  -> 200
   reply: Next: "Design review" at 2026-11-03T14:00:00Z.

5. Ten minutes later, her token has expired; two questions at once
   (these ran at the same time, so their lines are sorted)
   agent ->     GET  calendar /events  -> 200  (x2)
   agent ->     POST cal-auth /token  refresh_token  -> 200
   alice        POST agent    /ask  -> 200  (x2)
   reply: Next: "Design review" at 2026-11-03T14:00:00Z.  (x2)

6. Bob signs in and asks
   bob          GET  agent    /  -> 302 to /login
   bob          GET  agent    /login  -> 302 to idp/authorize
   bob          GET  idp      /authorize  scope="email openid" S256, state, nonce  -> 302 to agent/callback
   agent ->     POST idp      /token  authorization_code  -> 200
   bob          GET  agent    /callback  code, state, iss=idp  -> 200
   bob          GET  agent    /  -> 200
   page: signed in as bob@example.com
   bob          POST agent    /ask  -> 200
   reply: I can't reach that account (calendar: not connected). Connect it, then ask again.

7. A copy of alice's first refresh token is stolen
   thief        POST cal-auth /token  refresh_token  -> 401 invalid_client: client authentication failed
   thief+secret POST cal-auth /token  refresh_token  -> 400 invalid_grant: refresh token already used: every token from this grant is revoked
   agent ->     POST cal-auth /token  refresh_token  -> 400 invalid_grant: unknown or revoked refresh token
   alice        POST agent    /ask  -> 200
   reply: I can't reach that account (calendar: not connected: the connection was revoked). Connect it, then ask again.

8. Alice signs out
   alice        POST agent    /logout  -> 204
   copy         GET  agent    /  -> 302 to /login
  1. Alice signs in. Her browser goes to the identity provider and back, the agent service redeems the code itself, and the browser ends with a session cookie.
  2. She asks for her next meeting. The agent’s tool needs her calendar, which she hasn’t connected.
  3. She connects it. This is a second authorization, at the calendar’s own authorization server, which asks for offline_access and so returns a refresh token. The service stores it encrypted.
  4. She asks again, and the tool calls the calendar with her access token.
  5. Ten minutes later her access token has expired, and two questions arrive at once. Both tool calls need a fresh token, and the service sends one refresh for both.
  6. Bob signs in and asks. His agent can’t reach alice’s calendar, and it can’t reach his own until he connects it.
  7. A copy of alice’s first refresh token, the one rotated away in step 5, turns up in the wrong hands. Without the service’s client secret it is refused outright. With the secret, the calendar’s authorization server sees a used token presented again and revokes everything descended from it, so alice’s next question asks her to connect again.
  8. Alice signs out, and a copy of her old session cookie gets nothing.

Keep the tokens on the server

The service is a backend for frontend, the pattern RFC 10017 (OAuth 2.0 for Browser-Based Applications, August 2026) recommends first, in section 6.1. The OAuth client is the server, a confidential client with a secret of its own, and every token lives there. The browser gets an HttpOnly cookie that script can’t read, and a page with a script injected into it can’t take a token away, because the page never had one. Such a script can still send requests as the user while the page is open, which no token storage prevents. Keeping tokens off the browser takes away the part that outlives the page: a stolen refresh token works for weeks from anywhere.

mcpauth/agentweb/service.go
// Config describes an agent service.
type Config struct {
	BaseURL string // where browsers reach the service: https://agent.example.com

	// The identity provider users sign in with, and the service's
	// client there: a confidential client, since the secret never
	// leaves the server.
	Issuer, ClientID, ClientSecret string

	Providers map[string]Provider // services users can connect, by name
	Vault     *Vault
	Tools     map[string]Tool // the agent's tools, by name
	Model     Model

	Client *http.Client // for every request the service makes
	Now    func() time.Time
}

// A Provider is a service whose API the agent's tools call, once a user
// connects an account there.
type Provider struct {
	Issuer                       string // its authorization server
	AuthURL, TokenURL, RevokeURL string
	ClientID, ClientSecret       string
	Resource                     string   // its API, as a resource indicator (RFC 8707)
	Scopes                       []string // what the tools need, and offline_access

	// SendsIss says the authorization server puts iss in its answers
	// (RFC 9207), as its metadata's
	// authorization_response_iss_parameter_supported says: answers
	// without it are then refused.
	SendsIss bool
}

Start the sign-in

mcpauth/agentweb/service.go
// startLogin sends the browser to the identity provider. state ties the
// answer to this browser, nonce ties the ID token to this sign-in, and
// the PKCE verifier ties the code to this server: a code stolen on its
// way back is useless without it.
func (s *Service) startLogin(w http.ResponseWriter, r *http.Request) {
	p := s.remember(w, &pending{state: rand.Text(), nonce: rand.Text(),
		verifier: oauth2.GenerateVerifier()})
	u := s.signIn.AuthCodeURL(p.state, oidc.Nonce(p.nonce),
		oauth2.S256ChallengeOption(p.verifier))
	http.Redirect(w, r, u, http.StatusFound)
}

Three values go out with the browser, and each one stops a different attack:

  • state ties the answer to this browser. Without it, an attacker can finish their own sign-in in your browser, by getting it to open a callback URL carrying the attacker’s code, and you are using the agent as them.
  • nonce ties the ID token to this sign-in. The identity provider copies it into the ID token, so an ID token from another sign-in can’t be passed off as this one’s.
  • The PKCE verifier (RFC 7636) ties the code to this server. Only its hash goes out, and the code is worth nothing without the verifier. RFC 9700, the OAuth security best current practice, recommends it for confidential clients too, since a client secret doesn’t stop a code stolen on its way back from being redeemed by the client itself, in the attacker’s session.

All three are kept server-side, under a random ID in a short-lived cookie:

mcpauth/agentweb/service.go
// remember stores p and gives this browser a cookie naming it. The
// cookie is SameSite=Lax: it must come back on the authorization
// server's redirect, which another site starts.
func (s *Service) remember(w http.ResponseWriter, p *pending) *pending {
	id := rand.Text()
	p.expires = s.cfg.Now().Add(10 * time.Minute)
	s.mu.Lock()
	s.pending[id] = p
	s.mu.Unlock()
	http.SetCookie(w, &http.Cookie{Name: loginCookie, Value: id, Path: "/",
		MaxAge: 600, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
	return p
}

// recall takes the flow this browser started, once, and checks the
// answer belongs to it: the same state, from the authorization server
// it was sent to, and not an error. An iss in the answer must name that
// server (RFC 9207), and when the server says it always sends one, an
// answer without one is refused.
func (s *Service) recall(w http.ResponseWriter, r *http.Request,
	provider, issuer string, sendsIss bool) (*pending, error) {
	c, err := r.Cookie(loginCookie)
	if err != nil {
		return nil, errors.New("this browser started no sign-in")
	}
	s.mu.Lock()
	p := s.pending[c.Value]
	delete(s.pending, c.Value) // one answer per flow
	s.mu.Unlock()
	http.SetCookie(w, &http.Cookie{Name: loginCookie, Path: "/", MaxAge: -1,
		Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
	q := r.URL.Query()
	switch {
	case p == nil || p.provider != provider || s.cfg.Now().After(p.expires):
		return nil, errors.New("unknown or expired")
	case subtle.ConstantTimeCompare([]byte(q.Get("state")), []byte(p.state)) != 1:
		return nil, errors.New("the state doesn't match")
	case (sendsIss || q.Has("iss")) && q.Get("iss") != issuer:
		return nil, errors.New("the answer came from another authorization server")
	case q.Get("error") != "":
		return nil, fmt.Errorf("the authorization server said %s", q.Get("error"))
	}
	return p, nil
}

The login cookie is SameSite=Lax, because it must come back on the identity provider’s redirect, a navigation another site starts.

Finish it

mcpauth/agentweb/service.go
// finishLogin takes the identity provider's answer: it checks the answer
// belongs to the sign-in this browser started, redeems the code, checks
// the ID token, and starts a session.
func (s *Service) finishLogin(w http.ResponseWriter, r *http.Request) {
	p, err := s.recall(w, r, "", s.cfg.Issuer, s.idpIss)
	if err != nil {
		http.Error(w, "sign-in failed: "+err.Error(), http.StatusBadRequest)
		return
	}
	ctx := oidc.ClientContext(r.Context(), s.cfg.Client)
	tok, err := s.signIn.Exchange(ctx, r.URL.Query().Get("code"),
		oauth2.VerifierOption(p.verifier))
	if err != nil {
		http.Error(w, "sign-in failed: the code was refused", http.StatusBadRequest)
		return
	}
	raw, _ := tok.Extra("id_token").(string)
	id, err := s.ids.Verify(ctx, raw)
	if err != nil {
		http.Error(w, "sign-in failed: bad ID token", http.StatusBadRequest)
		return
	}
	var claims struct {
		Email    string `json:"email"`
		Verified bool   `json:"email_verified"`
		AZP      string `json:"azp"`
	}
	switch {
	case id.Claims(&claims) != nil:
		err = errors.New("unreadable claims")
	case subtle.ConstantTimeCompare([]byte(id.Nonce), []byte(p.nonce)) != 1:
		err = errors.New("the ID token is from another sign-in")
	case claims.AZP != "" && claims.AZP != s.cfg.ClientID:
		err = errors.New("the ID token was issued to another client")
	}
	if err != nil {
		http.Error(w, "sign-in failed: "+err.Error(), http.StatusBadRequest)
		return
	}
	s.startSession(w, id.Subject, claims.Email)
	// A page, not a redirect: a session cookie with SameSite=Strict
	// isn't sent on a redirect that began at another site, so the
	// browser moves on from here, a navigation this site starts.
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprint(w, `<!doctype html><meta http-equiv="refresh" content="0;url=/">`)
}
A sequence of three participants: the browser, the agent service, and the identity provider. The browser asks the agent service for /login and gets a login cookie and a redirect carrying state, nonce, and a PKCE challenge. The browser goes to the identity provider, where the user signs in, and comes back with a code, the state, and iss. The browser sends the callback with the login cookie; the agent service checks the state and iss, redeems the code at the identity provider with the verifier and its client secret, gets an ID token and an access token, checks the ID token and the nonce, and gives the browser a session cookie and nothing else.A sequence of three participants: the browser, the agent service, and the identity provider. The browser asks the agent service for /login and gets a login cookie and a redirect carrying state, nonce, and a PKCE challenge. The browser goes to the identity provider, where the user signs in, and comes back with a code, the state, and iss. The browser sends the callback with the login cookie; the agent service checks the state and iss, redeems the code at the identity provider with the verifier and its client secret, gets an ID token and an access token, checks the ID token and the nonce, and gives the browser a session cookie and nothing else.A sequence of three participants: the browser, the agent service, and the identity provider. The browser asks the agent service for /login and gets a login cookie and a redirect carrying state, nonce, and a PKCE challenge. The browser goes to the identity provider, where the user signs in, and comes back with a code, the state, and iss. The browser sends the callback with the login cookie; the agent service checks the state and iss, redeems the code at the identity provider with the verifier and its client secret, gets an ID token and an access token, checks the ID token and the nonce, and gives the browser a session cookie and nothing else.A sequence of three participants: the browser, the agent service, and the identity provider. The browser asks the agent service for /login and gets a login cookie and a redirect carrying state, nonce, and a PKCE challenge. The browser goes to the identity provider, where the user signs in, and comes back with a code, the state, and iss. The browser sends the callback with the login cookie; the agent service checks the state and iss, redeems the code at the identity provider with the verifier and its client secret, gets an ID token and an access token, checks the ID token and the nonce, and gives the browser a session cookie and nothing else.A sequence of three participants: the browser, the agent service, and the identity provider. The browser asks the agent service for /login and gets a login cookie and a redirect carrying state, nonce, and a PKCE challenge. The browser goes to the identity provider, where the user signs in, and comes back with a code, the state, and iss. The browser sends the callback with the login cookie; the agent service checks the state and iss, redeems the code at the identity provider with the verifier and its client secret, gets an ID token and an access token, checks the ID token and the nonce, and gives the browser a session cookie and nothing else.
Signing in, as in step 1 of the log. The code goes through the browser; the tokens never do.
  1. The answer must belong to this browser’s sign-in: the login cookie must name a sign-in in progress, the state must match, and the answer must come from the identity provider it was sent to. An iss in the answer must name that provider (RFC 9207), and when the provider’s metadata says it always sends one, an answer without one is refused. The sign-in is removed as it is read, so an answer works once.
  2. The code is redeemed with the verifier, and with the client secret, in the request’s Authorization header.
  3. The ID token is checked by go-oidc, the maintained OpenID Connect library for Go: its signature, with the algorithm pinned to ES256, its issuer, that its audience includes this client, and its expiry.
  4. The nonce is checked here, because go-oidc doesn’t: its verifier leaves nonce to the caller, and so does azp, the authorized party, which the next line checks when it is present.
  5. A new session starts, and everything else from the sign-in is dropped. The service keeps who signed in and doesn’t keep the tokens: it has no API to call with them.

The callback answers with a page rather than a redirect. The session cookie is SameSite=Strict, which browsers don’t send on a redirect that began at another site, so a redirect from the callback to / would arrive without it. A page that sends the browser on is a navigation this site starts, and the cookie goes with it.

TestSignInRefuses sends six answers that must fail: one for a sign-in another browser started, a changed state, an answer with no iss from a server that always sends one, an answer naming another issuer, the attacker’s code with the victim’s state (PKCE stops it at the token endpoint), and a nonce changed on its way to the identity provider.

mcpauth/agentweb/agentweb_test.go
// TestSignInRefuses: an answer from the identity provider signs a
// browser in only if it belongs to the sign-in that browser started.
func TestSignInRefuses(t *testing.T) {
	w := newTestWorld(t)
	// start begins a sign-in in b and returns the URL the identity
	// provider would send the browser back to.
	start := func(b *http.Client, change func(url.Values)) *url.URL {
		loc, _ := step(t, b, w.agent+"/login")
		authz, _ := url.Parse(loc)
		q := authz.Query()
		if change != nil {
			change(q)
		}
		authz.RawQuery = q.Encode()
		loc, _ = step(t, b, authz.String())
		back, _ := url.Parse(loc)
		return back
	}
	with := func(u *url.URL, k, v string) string {
		q := u.Query()
		q.Set(k, v)
		c := *u
		c.RawQuery = q.Encode()
		return c.String()
	}
	victim, attacker := w.browser("alice@example.com"), w.browser("mallory@example.com")
	for _, c := range []struct {
		name string
		send func() (int, string)
	}{
		{"an answer this browser never asked for", func() (int, string) {
			back := start(attacker, nil)
			return do(t, w.browser("alice@example.com"), "GET", back.String(), "", "")
		}},
		{"a changed state", func() (int, string) {
			return do(t, victim, "GET", with(start(victim, nil), "state", "guess"), "", "")
		}},
		{"an answer with no iss, from a server that always sends one", func() (int, string) {
			back := start(victim, nil)
			q := back.Query()
			q.Del("iss")
			back.RawQuery = q.Encode()
			return do(t, victim, "GET", back.String(), "", "")
		}},
		{"an answer naming another issuer", func() (int, string) {
			return do(t, victim, "GET", with(start(victim, nil), "iss", "https://evil.example"), "", "")
		}},
		{"the attacker's code, with the victim's state", func() (int, string) {
			mine := start(attacker, nil)
			theirs := start(victim, nil)
			return do(t, victim, "GET", with(theirs, "code", mine.Query().Get("code")), "", "")
		}},
		{"a nonce changed on the way to the identity provider", func() (int, string) {
			back := start(victim, func(q url.Values) { q.Set("nonce", "attacker's") })
			return do(t, victim, "GET", back.String(), "", "")
		}},
	} {
		code, body := c.send()
		if code != http.StatusBadRequest || !strings.Contains(body, "sign-in failed") {
			t.Errorf("%s: %d %q, want a refusal", c.name, code, body)
		}
	}
}

What the ID token is for

Its subject, sub, is who the user is to this identity provider. Key everything on the issuer and the subject together, never on the email: addresses change, get reassigned, and at some providers can be set by the user. The demo’s subjects happen to be addresses, which keeps the log readable.

The ID token is not an access token. Its audience is the agent service, and an API that accepted it would accept a token issued for someone else. The identity provider here types it JWT and its access tokens at+jwt, and the resource server’s verifier refuses anything not typed as an access token.

The session

mcpauth/agentweb/service.go
// A session is a signed-in browser. The browser holds only its ID.
type session struct {
	user, email   string
	started, seen time.Time
}

// startSession signs the browser in as user. Every sign-in gets a new
// session ID, never one the browser brought with it, so an attacker who
// planted a session ID before sign-in doesn't share the session after.
func (s *Service) startSession(w http.ResponseWriter, user, email string) {
	id, now := rand.Text(), s.cfg.Now()
	s.mu.Lock()
	s.sessions[id] = &session{user: user, email: email, started: now, seen: now}
	s.mu.Unlock()
	http.SetCookie(w, &http.Cookie{Name: sessionCookie, Value: id, Path: "/",
		Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode})
}

// session returns the browser's session, if it has one that hasn't been
// idle for 30 minutes or open for 12 hours.
func (s *Service) session(r *http.Request) (*session, string) {
	c, err := r.Cookie(sessionCookie)
	if err != nil {
		return nil, ""
	}
	now := s.cfg.Now()
	s.mu.Lock()
	defer s.mu.Unlock()
	ss := s.sessions[c.Value]
	if ss == nil || now.Sub(ss.seen) > idleTimeout || now.Sub(ss.started) > maxSession {
		delete(s.sessions, c.Value)
		return nil, ""
	}
	ss.seen = now
	return ss, c.Value
}

// signedIn wraps a handler that needs a session. A request that
// changes something must also come from the service's own pages: a
// browser sends Origin on every POST, and another site can't set it
// to this one.
func (s *Service) signedIn(h func(http.ResponseWriter, *http.Request,
	*session)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ss, _ := s.session(r)
		if ss == nil {
			http.Error(w, "sign in first", http.StatusUnauthorized)
			return
		}
		if r.Method == http.MethodPost && r.Header.Get("Origin") != s.origin() {
			http.Error(w, "cross-site request refused", http.StatusForbidden)
			return
		}
		h(w, r, ss)
	}
}

The cookie’s name starts with __Host-Http-, the prefix RFC 10017 asks for: __Host- makes browsers refuse it unless it is Secure, has Path=/, and names no domain, so a subdomain can’t set it, and Http- requires HttpOnly, so no script can set it or read it. Every sign-in gets a new session ID, so an ID planted in the browser before sign-in isn’t the one that becomes signed in. A session ends after 30 minutes idle or 12 hours in all, and signing out deletes it on the server, so a copy of the cookie stops working too, which is the last line of step 8.

A POST must carry an Origin header naming the service. Browsers send one on every POST, and a page on another site can’t make it say this site, so a form on that site can’t make a signed-in user’s browser ask the agent to do something. With SameSite=Strict as well, the cookie isn’t sent on such a request in the first place.

Connect the user’s accounts

The calendar is a separate service with its own authorization server, where the agent service is registered as a client of its own. Connecting is a second authorization code flow, started by a signed-in user:

mcpauth/agentweb/connect.go
// startConnect sends a signed-in user to a provider to grant the agent
// access to their account there, asking for the scopes the tools need
// and offline_access, for a refresh token: the agent works when the
// user isn't there to sign in again.
func (s *Service) startConnect(w http.ResponseWriter, r *http.Request, ss *session) {
	name, prov, ok := s.provider(r)
	if !ok {
		http.NotFound(w, r)
		return
	}
	p := s.remember(w, &pending{state: rand.Text(),
		verifier: oauth2.GenerateVerifier(), provider: name, user: ss.user})
	u := prov.oauth(s.callbackURL(name)).AuthCodeURL(p.state,
		oauth2.S256ChallengeOption(p.verifier),
		oauth2.SetAuthURLParam("resource", prov.Resource))
	http.Redirect(w, r, u, http.StatusSeeOther)
}

// finishConnect redeems the provider's code and stores the credential
// under the user who started the connection, who must be the one
// signed in now.
func (s *Service) finishConnect(w http.ResponseWriter, r *http.Request, ss *session) {
	name, prov, ok := s.provider(r)
	if !ok {
		http.NotFound(w, r)
		return
	}
	p, err := s.recall(w, r, name, prov.Issuer, prov.SendsIss)
	if err == nil && p.user != ss.user {
		err = errors.New("started by another user")
	}
	if err != nil {
		http.Error(w, "connecting failed: "+err.Error(), http.StatusBadRequest)
		return
	}
	ctx := oidc.ClientContext(r.Context(), s.cfg.Client)
	tok, err := prov.oauth(s.callbackURL(name)).Exchange(ctx,
		r.URL.Query().Get("code"), oauth2.VerifierOption(p.verifier),
		oauth2.SetAuthURLParam("resource", prov.Resource))
	if err != nil || tok.RefreshToken == "" {
		http.Error(w, "connecting failed: no refresh token", http.StatusBadGateway)
		return
	}
	err = s.cfg.Vault.Put(ss.user, name, Token{Access: tok.AccessToken,
		Refresh: tok.RefreshToken, Expiry: s.expiry(tok)})
	if err != nil {
		http.Error(w, "connecting failed", http.StatusInternalServerError)
		return
	}
	fmt.Fprintf(w, "connected %s\n", name)
}

It asks for the scopes the tools need and offline_access, which is what gets a refresh token: the agent works for the user when they aren’t there to sign in again. It names the API with resource (RFC 8707), so the access token is issued for the calendar API and no other. The callback checks the answer exactly as the sign-in’s does, against the calendar’s issuer this time, and checks that the user signed in now is the one who started connecting.

Store each credential for one user

mcpauth/agentweb/vault.go
// A Vault keeps users' credentials for the providers they connected,
// encrypted with AES-256-GCM. Each row is sealed with its user and
// provider as additional data, so a row copied under another user's
// key, by a bug or by someone with write access to the table, fails to
// open instead of handing one user's account to another.
type Vault struct {
	aead cipher.AEAD
	mu   sync.Mutex
	rows map[string][]byte // stands in for a table: row key to nonce and ciphertext
}

// NewVault returns a vault that encrypts with key, 32 bytes. In
// production the key comes from a key management service, never from
// the database that holds the rows.
func NewVault(key []byte) (*Vault, error) {
	block, err := aes.NewCipher(key)
	if err != nil || len(key) != 32 {
		return nil, errors.New("vault: the key must be 32 bytes")
	}
	aead, err := cipher.NewGCM(block)
	if err != nil {
		return nil, fmt.Errorf("vault: %w", err)
	}
	return &Vault{aead: aead, rows: map[string][]byte{}}, nil
}

// Put stores t as user's credential at provider, replacing any before.
func (v *Vault) Put(user, provider string, t Token) error {
	plain, err := json.Marshal(t)
	if err != nil {
		return fmt.Errorf("vault: %w", err)
	}
	nonce := make([]byte, v.aead.NonceSize())
	rand.Read(nonce) // never returns an error
	ad := rowKey(user, provider)
	sealed := v.aead.Seal(nonce, nonce, plain, ad)
	v.mu.Lock()
	defer v.mu.Unlock()
	v.rows[string(ad)] = sealed
	return nil
}

// Get returns user's credential at provider, or ErrNotConnected.
func (v *Vault) Get(user, provider string) (Token, error) {
	var t Token
	ad := rowKey(user, provider)
	v.mu.Lock()
	sealed, ok := v.rows[string(ad)]
	v.mu.Unlock()
	n := v.aead.NonceSize()
	if !ok || len(sealed) < n {
		return t, ErrNotConnected
	}
	plain, err := v.aead.Open(nil, sealed[:n], sealed[n:], ad)
	if err != nil {
		return t, fmt.Errorf("vault: %s's credential at %s doesn't open: %w",
			user, provider, err)
	}
	if err := json.Unmarshal(plain, &t); err != nil {
		return t, fmt.Errorf("vault: %w", err)
	}
	return t, nil
}
  1. Each row is sealed with AES-256-GCM, with its user and provider as additional data. The ciphertext opens only under the same user and provider, so a row copied to bob’s key, by a bug in a query or by someone with write access to the table, fails to open instead of giving bob alice’s calendar.
  2. Opening checks the same binding, and any change to the row fails it.

The key comes from a key management service, never from the database the rows live in, so a copy of the table alone is ciphertext. In production the rows also carry a key ID, so the key can be rotated without rewriting every row at once.

mcpauth/agentweb/agentweb_test.go
// TestVault: a row opens only as the user and provider it was stored
// for, unchanged, with the key it was sealed with.
func TestVault(t *testing.T) {
	key := bytes.Repeat([]byte{1}, 32)
	v, err := NewVault(key)
	if err != nil {
		t.Fatal(err)
	}
	if err := v.Put("alice", "calendar", Token{Access: "a", Refresh: "r"}); err != nil {
		t.Fatal(err)
	}
	if got, err := v.Get("alice", "calendar"); err != nil || got.Refresh != "r" {
		t.Fatalf("Get = %+v, %v", got, err)
	}
	alices := v.rows[string(rowKey("alice", "calendar"))]
	other, _ := NewVault(bytes.Repeat([]byte{2}, 32))
	for _, c := range []struct {
		name  string
		v     *Vault
		user  string
		setup func()
	}{
		{"copied to bob's row", v, "bob", func() {
			v.rows[string(rowKey("bob", "calendar"))] = alices
		}},
		{"one byte changed", v, "alice", func() {
			bad := bytes.Clone(alices)
			bad[len(bad)-1] ^= 1
			v.rows[string(rowKey("alice", "calendar"))] = bad
		}},
		{"opened with another key", other, "alice", func() {
			other.rows[string(rowKey("alice", "calendar"))] = alices
		}},
	} {
		c.setup()
		if _, err := c.v.Get(c.user, "calendar"); err == nil ||
			!strings.Contains(err.Error(), "doesn't open") {
			t.Errorf("%s: Get = %v, want it refused", c.name, err)
		}
	}
}

Refresh once

The calendar’s authorization server rotates refresh tokens: each works once, and the answer carries the next. Presenting a used one means two parties hold copies, the client and a thief, and the server can’t tell which is which, so it revokes the whole family, as RFC 9700 describes in section 4.14.2:

mcpauth/authserver/oidc_test.go
// TestRefreshRotation: each refresh token works once, and using one a
// second time revokes every token descended from the same grant, the
// one the rightful client holds now included.
func TestRefreshRotation(t *testing.T) {
	srv := oidcSetup(t)
	_, body := redeem(t, srv, "s3cret",
		codeFor(t, srv, "issues:read offline_access", resource, ""), resource)
	first, _ := body["refresh_token"].(string)
	refresh := func(rt string) (int, map[string]any) {
		return tokenReq(t, srv, "/token", "s3cret", url.Values{
			"grant_type": {"refresh_token"}, "refresh_token": {rt}})
	}
	status, body := refresh(first)
	second, _ := body["refresh_token"].(string)
	if status != http.StatusOK || second == "" || second == first {
		t.Fatalf("first refresh: %d, rotated %v", status, second != first)
	}
	if status, body := refresh(first); status != http.StatusBadRequest ||
		body["error"] != "invalid_grant" {
		t.Errorf("the used token again: %d %v", status, body)
	}
	if status, _ := refresh(second); status != http.StatusBadRequest {
		t.Errorf("the newest token after the reuse: %d, want it revoked too", status)
	}
}

Rotation is good against theft and hard on concurrency. An agent runs tools in parallel, and when the access token expires, every tool call that needs it finds it expired at once. If each refreshes, all but the first present a used refresh token, and the provider revokes the connection: the service locks itself out with no attacker involved.

mcpauth/agentweb/connect.go
// TokenFor returns an access token for user's account at provider,
// refreshing it when it has run out. Calls for one user and provider
// share a refresh: with rotation, every refresh token works once, and
// two refreshes sent with the same one look to the provider like a
// stolen copy in use, so it revokes both.
func (s *Service) TokenFor(ctx context.Context, user, provider string) (string, error) {
	tok, err, _ := s.flight.Do(string(rowKey(user, provider)), func() (any, error) {
		return s.current(context.WithoutCancel(ctx), user, provider)
	})
	if err != nil {
		return "", err //nolint:wrapcheck // current's errors name the provider
	}
	return tok.(string), nil
}

// The margin before expiry at which a token counts as run out, so a
// request doesn't set off with a token that expires on the way.
const margin = 30 * time.Second

func (s *Service) current(ctx context.Context, user, name string) (string, error) {
	t, err := s.cfg.Vault.Get(user, name)
	if err != nil {
		return "", fmt.Errorf("%s: %w", name, err)
	}
	if s.cfg.Now().Before(t.Expiry.Add(-margin)) {
		return t.Access, nil
	}
	ctx, cancel := context.WithTimeout(oidc.ClientContext(ctx, s.cfg.Client),
		10*time.Second)
	defer cancel()
	prov := s.cfg.Providers[name]
	nt, err := prov.oauth("").TokenSource(ctx,
		&oauth2.Token{RefreshToken: t.Refresh}).Token()
	var re *oauth2.RetrieveError
	if errors.As(err, &re) && re.ErrorCode == "invalid_grant" {
		s.cfg.Vault.Delete(user, name)
		return "", fmt.Errorf("%s: %w: the connection was revoked", name, ErrNotConnected)
	}
	if err != nil {
		return "", fmt.Errorf("%s: refresh: %w", name, err)
	}
	next := Token{Access: nt.AccessToken, Refresh: nt.RefreshToken, Expiry: s.expiry(nt)}
	if next.Refresh == "" {
		next.Refresh = t.Refresh // the provider doesn't rotate
	}
	if err := s.cfg.Vault.Put(user, name, next); err != nil {
		return "", err
	}
	return next.Access, nil
}
  1. Calls for one user and provider share a refresh, through singleflight, and the refresh runs on a context that ignores the caller’s cancellation. Once the provider has rotated the token, the new one must be stored, or the service holds only a used token and the next refresh revokes the connection. A caller giving up doesn’t get to stop that halfway.
  2. The refresh token is redeemed with the client secret. The service computes the new expiry with its own clock from expires_in.
  3. A refused refresh token means the connection is gone, revoked by the user at the provider or by reuse detection. The service forgets it, and the tool tells the model the user must connect again, which is how step 7 ends.
  4. The new token is stored before it is used.

singleflight coordinates calls in one process. Several replicas of the service need the same guarantee across processes, a lock on the user and provider’s row, for example, held while refreshing. Some providers allow a grace period in which the previous refresh token still works, Okta’s for one, which softens the race; it is not a substitute for not having it.

mcpauth/agentweb/agentweb_test.go
// TestOneRefreshAtATime: many tool calls finding the token expired at
// once share one refresh. Each sending its own would reuse the refresh
// token, and the provider would revoke the connection.
func TestOneRefreshAtATime(t *testing.T) {
	w := newTestWorld(t)
	b := w.browser("alice@example.com")
	w.signIn(t, b)
	w.connect(t, b)
	w.advance(10 * time.Minute)
	var wg sync.WaitGroup
	toks := make([]string, 20)
	errs := make([]error, 20)
	for i := range toks {
		wg.Go(func() {
			toks[i], errs[i] = w.svc.TokenFor(t.Context(), "alice@example.com", "calendar")
		})
	}
	wg.Wait()
	for i := range toks {
		if errs[i] != nil || toks[i] != toks[0] {
			t.Fatalf("call %d: %v, or a different token", i, errs[i])
		}
	}
	if n := w.refreshes.Load(); n != 1 {
		t.Errorf("%d refreshes, want 1", n)
	}
	if reply := w.ask(t, b); !strings.Contains(reply, "Design review") {
		t.Errorf("after the refresh: %q", reply)
	}
}

Step 7 shows the other reason the service is a confidential client: a refresh token alone is useless. RFC 9700 binds a confidential client’s refresh tokens to its client authentication, so a token copied out of a backup needs the client secret too, and the secret lives somewhere the backup doesn’t.

The model never sees a token

mcpauth/agentweb/connect.go
// ask runs one turn of the agent for the signed-in user. The model
// picks the tool and its arguments; the user it runs for comes from
// the session. Neither the model nor the browser ever sees a token.
func (s *Service) ask(w http.ResponseWriter, r *http.Request, ss *session) {
	var req struct {
		Question string `json:"question"`
	}
	r.Body = http.MaxBytesReader(w, r.Body, 64<<10)
	if err := json.UnmarshalRead(r.Body, &req); err != nil {
		http.Error(w, "a JSON question is required", http.StatusBadRequest)
		return
	}
	name, args := s.cfg.Model(req.Question)
	tool, ok := s.cfg.Tools[name]
	reply := "I have no tool for that."
	if ok {
		out, err := tool(r.Context(), s, ss.user, args)
		switch {
		case errors.Is(err, ErrNotConnected):
			reply = fmt.Sprintf("I can't reach that account (%v). Connect it,"+
				" then ask again.", err)
		case err != nil:
			reply = "That didn't work: " + err.Error()
		default:
			reply = out
		}
	}
	w.Header().Set("Content-Type", "application/json")
	_ = json.MarshalWrite(w, map[string]string{"reply": reply})
}

The model picks a tool and its arguments. Who the tool runs as comes from the session, and a tool gets its credential from TokenFor, by that user’s name:

mcpauth/agentweb/tools.go
// NextMeeting is a tool that reads the user's next meeting from the
// calendar API at api, with the user's own credential for the provider
// named calendar.
func NextMeeting(api string) Tool {
	return func(ctx context.Context, s *Service, user string, _ []byte) (string, error) {
		tok, err := s.TokenFor(ctx, user, "calendar")
		if err != nil {
			return "", err
		}
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, api+"/events", nil)
		if err != nil {
			return "", fmt.Errorf("next_meeting: %w", err)
		}
		req.Header.Set("Authorization", "Bearer "+tok)
		resp, err := s.cfg.Client.Do(req)
		if err != nil {
			return "", fmt.Errorf("next_meeting: %w", err)
		}
		defer resp.Body.Close()
		if resp.StatusCode != http.StatusOK {
			return "", fmt.Errorf("next_meeting: the calendar answered %s", resp.Status)
		}
		var events []struct {
			Title string `json:"title"`
			Start string `json:"start"`
		}
		b, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
		if err == nil {
			err = json.Unmarshal(b, &events)
		}
		if err != nil {
			return "", fmt.Errorf("next_meeting: %w", err)
		}
		if len(events) == 0 {
			return "Nothing on your calendar.", nil
		}
		return fmt.Sprintf("Next: %q at %s.", events[0].Title, events[0].Start), nil
	}
}

No token passes through the model’s context, so no prompt can get one printed, and an argument naming another user changes nothing: TestToolRunsAsSessionUser has the model ask for alice’s calendar while bob is signed in, and the answer is that bob hasn’t connected one.

Disconnecting revokes

mcpauth/agentweb/connect.go
// disconnect revokes the user's refresh token at the provider (RFC
// 7009), which also ends every token descended from it, and then
// forgets the credential. Deleting the row alone would leave a working
// refresh token in every backup of the table.
func (s *Service) disconnect(w http.ResponseWriter, r *http.Request, ss *session) {
	name, prov, ok := s.provider(r)
	if !ok {
		http.NotFound(w, r)
		return
	}
	t, err := s.cfg.Vault.Get(ss.user, name)
	if err != nil {
		http.Error(w, "not connected", http.StatusNotFound)
		return
	}
	if err := s.revoke(r.Context(), prov, t.Refresh); err != nil {
		http.Error(w, "the provider didn't confirm the revocation", http.StatusBadGateway)
		return
	}
	s.cfg.Vault.Delete(ss.user, name)
	w.WriteHeader(http.StatusNoContent)
}

Deleting the row isn’t enough: every backup of the table holds the refresh token, and to the provider it is still good. Revoking it at the provider’s revocation endpoint (RFC 7009) ends it, and the family descended from it, everywhere at once. Access tokens already issued are JWTs that the provider doesn’t track, so they run until they expire, five minutes here.

With Okta

The example’s identity provider and the calendar’s authorization server are a test double. With Okta as the identity provider, the configuration becomes Okta’s values, and a few of its defaults matter:

  • The issuer. A custom authorization server’s issuer is https://{yourOktaDomain}/oauth2/{authorizationServerId}, https://{yourOktaDomain}/oauth2/default for the default one, with its discovery document at /.well-known/openid-configuration under that path. go-oidc compares the issuer in the document with the one you configured exactly.
  • Which authorization server. For signing in, either works. Access tokens your own APIs will validate must come from a custom authorization server: Okta’s documentation says access tokens from the org authorization server aren’t intended for validation by your own apps or resource servers.
  • The client. Register the agent service as a web application, a confidential client, and turn on PKCE for it as well.
  • Refresh tokens. Ask for offline_access and enable the refresh token grant for the app. Rotation is on by default only for single-page apps; web apps get persistent refresh tokens unless you turn rotation on, with a grace period of 0 to 60 seconds, 30 by default. Reusing a rotated token past the grace period invalidates the newest one and the access tokens issued since.
  • The iss parameter. Read authorization_response_iss_parameter_supported in the metadata; the service requires iss only when the provider says it sends one.
  • The user’s key. Okta’s sub is a stable user ID; key on it with the issuer, not on the email.

The code here was tested against its own authorization servers only. Run the same tests against a test tenant before relying on it.

Why this way and not another

  • Tokens in the browser. A single-page app as a public OAuth client is allowed, with a token store any injected script can read, and RFC 10017 describes the backend for frontend first, as the architecture that keeps tokens out of the browser altogether. An agent’s tokens reach the user’s other accounts, which raises the stakes.
  • Using the sign-in’s access token for the calendar. It is issued for the identity provider, and the calendar isn’t. Each API gets a token issued for it.
  • Stateless sessions in a signed cookie. No lookup per request, and no way to end one: signing out can’t stop a copy of the cookie, and neither can an administrator.
  • Encryption without the binding. It protects against someone reading the table, and not against a row put under the wrong user, which is the mistake the binding catches.
  • Refreshing wherever a token runs out. Fine without rotation, and with it, a parallel agent revokes its own connections.
  • A key per user pasted into settings. No expiry, no scopes, no revocation at the provider, and the user’s whole account.

Mistakes to avoid

  • Skipping the nonce check. go-oidc’s verifier doesn’t do it.
  • Keying users by email. Use the issuer and sub.
  • Letting a refresh be cancelled halfway. Finish it and store the result.
  • Refreshing in parallel with rotating tokens. Share one refresh per user and provider.
  • Deleting a credential without revoking it.
  • Sending an ID token to an API.
  • Ending a session only in the browser. Delete it on the server.

Try it

From the code/mcpauth directory of a clone of the companion repository:

terminal
$ go run ./cmd/agentweb
$ go test -race ./...
  1. In agentweb/connect.go, have TokenFor call s.current directly instead of through s.flight.Do, and run go test ./agentweb -run TestOneRefreshAtATime. The twenty tool calls refresh twenty times, and the provider revokes the connection.
  2. Remove context.WithoutCancel from TokenFor and run go test ./agentweb -run TestRefreshSurvivesCancel. A caller that has given up now stops the refresh.
  3. In agentweb/service.go, delete the nonce comparison and run go test ./agentweb -run TestSignInRefuses. The sign-in with the changed nonce goes through.
  4. In agentweb/vault.go, pass nil for the additional data to both Seal and Open, and run go test ./agentweb -run TestVault. Alice’s row, copied under bob, opens as bob’s.

Undo your edits with git restore . in the code directory.