Implement Secure Cross App Access (XAA) in Go

Picture this: a salesperson at your company asks the company's AI assistant to book a dinner with a customer and log it against the deal in the sales pipeline app. They're already signed in to the assistant through the company's single sign-on, but the pipeline app's Model Context Protocol (MCP) server still needs proof that the assistant is acting on that salesperson's behalf, and the company's security team wants a say in what it can touch. That's where Cross App Access (XAA) comes in: the company's identity provider checks its policies and issues the assistant a signed identity assertion, which the assistant exchanges for a scoped access token the pipeline app accepts. No second sign-in and no consent screen.

In this post, we'll understand XAA, then run a small Go web app called AI Notes Assistant that uses XAA to fetch a user's to-do items from a protected MCP server and turn them into notes, no OAuth consent screen required. You'll clone the finished project, run it against the XAA playground, and walk through the Go code behind each step of the flow.

To follow along, you'll need:

  • Git to clone the project
  • Go 1.26 or newer, and some familiarity with reading Go (the Tour of Go is a good way to get up to speed)
  • A code editor or IDE, such as VS Code or GoLand, to open the project, edit config.json, and read the Go code
  • A terminal (the one built into your IDE works)
  • An email address to use on xaa.dev, where you'll register AI Notes Assistant as a requester app (xaa.dev doesn't create an account or ask for a password; it uses the email only to show you the apps you've registered)

What is Cross App Access (XAA)?

Before we start building, it's important to understand Cross App Access (XAA). XAA is an emerging standard that helps apps and AI agents securely access other apps on a signed-in user's behalf. Instead of relying on shared user credentials or static API keys, it lets an organization's identity provider (IdP), such as Okta, help manage that access.

For example, an employee might ask an AI assistant to summarize a project document. XAA helps the assistant request access to the project app, while the identity provider's policies and the app's permissions determine what it can see.

You can think of XAA like an agreed process for using a partner company's building. Your employee badge won't open the partner's doors by itself; the partner needs a trusted way to verify who you are and grant the right level of access. XAA provides a similar way for apps to verify an agent's access on a user's behalf.

While the flow is sophisticated, it relies on two standard interactions, each defined in a Request for Comments (RFC) document published by the Internet Engineering Task Force (IETF):

  1. RFC 8693 (Token Exchange): the requesting app hands its OpenID Connect (OIDC) ID token to the enterprise IdP and asks for an Identity Assertion Authorization Grant (ID-JAG)
  2. RFC 7523 (JSON Web Token (JWT) Bearer Grant): the app hands that ID-JAG to the resource's own authorization server and gets back a scoped access token, ready to use against the real API

Before those two exchanges, the user signs in with OIDC using Proof Key for Code Exchange (PKCE), which is Step 1 in the diagram below.

Sequence diagram in four steps. In step 1 the user signs in through AI Notes Assistant and the enterprise IdP using OIDC and PKCE, and the IdP returns an ID token. In step 2 the app exchanges the ID token for an ID-JAG at the IdP using RFC 8693. In step 3 the app sends the ID-JAG to the resource authorization server using the RFC 7523 JWT bearer grant and receives a scoped access token. In step 4 the app calls the MCP server with the access token and gets resource data back

Look at the above flow diagram for a second before moving on: you can see zero manual consent prompts anywhere. In the rest of this post, you'll run the app and read the Go code behind each of the four steps, checking the dashboard after each one to see it work. This post covers the client side in Go. If you want the policy side of the story, check out:

Integrate Your Enterprise AI Tools with Cross App Access (XAA)

Manage user and non-human identities, including AI in the enterprise with Cross App Access (XAA)

Get the project

The okta-go-mcp-xaa-lab repository has everything you need: the web server, session handling, page templates, the dashboard that streams each step as it runs, and the code for the four steps of the XAA flow. Open a terminal, clone the repository, and pull down its dependencies:

git clone https://github.com/oktadev/okta-go-mcp-xaa-lab
cd okta-go-mcp-xaa-lab
go mod tidy

Then open the okta-go-mcp-xaa-lab folder in your IDE (in VS Code, run code . from the same terminal, or use File > Open Folder). Keep it open: you'll edit config.json in the next section and read the Go code in the sections after that. Run every command in this post from the project's root folder, the one containing main.go and config.json.

Take a look around. These are the files the XAA flow lives in:

  • internal/oidcauth/oidc.go has the sign-in handlers. HandleLogin starts the OIDC and PKCE sign-in, and HandleCallback finishes it
  • internal/xaa/tokenexchange.go has the two token exchanges, exchangeForJAG and requestAccessToken, plus GetAccessToken, which chains them
  • internal/mcpnotes/client.go has the MCP client. bearerTransport attaches the access token, and Fetch connects to the MCP server and reads the data

Register your app with xaa.dev

Next, register AI Notes Assistant as a requester app on xaa.dev:

  1. Open the xaa.dev registration page, enter your email address, and click Continue. Then, under Register an OIDC requesting app, click + Register New App.
  2. Set the redirect URI to http://localhost:8080/callback and the post-logout redirect URI to http://localhost:8080/logged-out
  3. Under Add Resource, pick ToDo MCP Server and add the connection
  4. Keep the xaa.dev page open. You'll copy the client ID and secrets it generates into config.json in the next section.
xaa.dev Edit App screen showing the requesting app's name, redirect URIs, and post-logout redirect URI configured for AI Notes Assistant

Configure and run the app

In your IDE, open config.json in the project root. It ships with placeholder values like <your-client-id>; replace them with the values from your xaa.dev registration. clientId and clientSecret come from the app you just registered; mcpClientId and mcpClientSecret are a separate pair xaa.dev issues for the MCP resource connection, the same two client IDs the code uses in the token exchanges you'll see shortly. sessionSecret isn't issued by xaa.dev at all, it's any long random string you generate yourself:

xaa.dev app registration card and a sample token request annotated with clientId, clientSecret, mcpClientId, and mcpClientSecret, showing where each config.json value comes from
{
  "xaa": {
    "clientId":        "<your-client-id>",
    "clientSecret":    "<your-client-secret>",
    "idpBaseUrl":      "https://idp.xaa.dev",

    "mcpClientId":     "<your-mcp-client-id>",
    "mcpClientSecret": "<your-mcp-client-secret>",

    "authServerUrl":   "https://auth.resource.xaa.dev",
    "mcpServerUrl":    "https://mcp.xaa.dev/mcp",
    "resourceUri":     "todo0://todos",
    "scope":           "todos.read mcp.access",

    "redirectUri":     "http://localhost:8080/callback",
    "sessionSecret":   "<any-long-random-string>"
  },
  "saml": { "enabled": false },
  "port": 8080
}

Git tracks config.json, so don't commit it, or push a fork of the project, once it holds your client secrets.

The file in the repo has a few extra placeholder values under saml. Leave them alone: "enabled": false keeps Security Assertion Markup Language (SAML) sign-in switched off, and this post only uses OIDC.

Save the file. Then, in your terminal, from the project root, start the server:

go run .

The terminal prints a line ending in AI Notes Assistant listening on http://localhost:8080 and stays running; leave it open. In your browser, go to http://localhost:8080. You'll see the AI Notes Assistant home screen with a Sign in button.

Click Sign in and go through the flow once. You'll sign in at the identity provider with a test email, verify with the code the playground asks for (xaa.dev runs in demo mode, so any 6-digit code works), land on the AI Notes Assistant home screen, and see the dashboard with all four steps checked off, the access token, its claims, and the notes pulled from the resource server. The app starts the analysis for you after sign-in, and you can run it again any time with Analyze My Notes. Leave the server running while you read through the code below.

Four panel walkthrough of running the Go MCP app with xaa.dev, showing signing in at the identity provider, verifying identity with a demo six digit code, the AI Notes Assistant home screen, and the dashboard with the completed XAA flow steps, access token, token claims, and notes

Walk through the XAA flow in Go

Now it's time to read the code. AI Notes Assistant runs through the flow in four steps, and each step below maps to an entry on the dashboard. In each section, you'll open the function in the file named in the heading comment, see how it works, then run the app and check the result.

Sign the user in with OIDC and PKCE

A user clicks sign in, and the app redirects them to the IdP using OIDC. HandleLogin does one thing most frameworks handle for you automatically: it builds its own PKCE challenge. PKCE stops an attacker who intercepts the authorization code from redeeming it, because only this app holds the matching verifier.

Open internal/oidcauth/oidc.go and find HandleLogin. Here it is (the full version also signs out any existing session before it starts):

// internal/oidcauth/oidc.go
func (a *Auth) HandleLogin(w http.ResponseWriter, r *http.Request) {
    verifier := oauth2.GenerateVerifier() // a random PKCE verifier, unique to this login attempt
    state := randString()                 // guards the redirect back against cross-site request forgery (CSRF)
    nonce := randString()                 // ties whatever ID token comes back to this exact attempt

    // save all three in a short-lived cookie so HandleCallback can read them back
    flow, _ := a.flowCookies.Get(r, flowCookieName)
    flow.Values["state"] = state
    flow.Values["verifier"] = verifier
    flow.Values["nonce"] = nonce
    if err := flow.Save(r, w); err != nil {
        http.Error(w, "failed to start login", http.StatusInternalServerError)
        return
    }

    authURL := a.oauth2Cfg.AuthCodeURL(state, oauth2.S256ChallengeOption(verifier), oidc.Nonce(nonce))
    http.Redirect(w, r, authURL, http.StatusFound) // send the browser to the IdP
}

Note: The cookie matters because the app doesn't keep any other record of this login attempt. The IdP authenticates the user and redirects back with a code, and HandleCallback, right below HandleLogin, reads the cookie to finish the job. It compares the state on the redirect to the saved one, redeems the code with the saved verifier, verifies the ID token it gets back against the saved nonce, and drops the token into the session. If the cookie is missing, the callback can't match the state, so it quietly redirects back to / and sign-in never completes. Nothing downstream trusts this token yet, though; it only proves identity to this one app.

Try it: with the app still running, open a second terminal and run:

curl -i http://localhost:8080/login

The response is a 302 Found. Its Location header is the IdP's authorize URL, https://idp.xaa.dev/authorize?.... Find code_challenge (the PKCE challenge, derived from the verifier), state, and nonce in it. HandleLogin generated all three for this request, and they're different every time you run the command. curl doesn't follow the redirect, so you can read the URL without signing in.

Also find the Set-Cookie: oidc_flow=... header. That's the cookie holding the state, verifier, and nonce for HandleCallback. It's HttpOnly and expires after five minutes (Max-Age=300). The browser sends it back with the callback request, so the app can finish the sign-in.

Now look back at the sign-in you did in the browser. Clicking Sign in sent you to idp.xaa.dev and back to localhost:8080/callback, where HandleCallback verified the ID token and stored it in your session. On the dashboard, the Step 1, User Login (OIDC) entry reads "ID Token obtained from session". The app then runs the rest of the flow on its own, so the next three entries fill in too. We'll look at each of them in the sections below.

Exchange the ID token for an ID-JAG with RFC 8693

This is the actual hand-off. The app takes the ID token from Step 1 and sends it to the IdP, asking to trade it for an ID-JAG, a short-lived, signed statement that this exact user is who they claim to be.

Open internal/xaa/tokenexchange.go and find exchangeForJAG. Here's the core of it:

// internal/xaa/tokenexchange.go
func exchangeForJAG(ctx context.Context, cfg config.XaaConfig, idToken string) (string, error) {
    fields := url.Values{
        "grant_type":           {"urn:ietf:params:oauth:grant-type:token-exchange"}, // this is a token exchange, per RFC 8693
        "requested_token_type": {"urn:ietf:params:oauth:token-type:id-jag"},          // ask specifically for an ID-JAG
        "subject_token":        {idToken},                                            // the ID token proving who signed in
        "subject_token_type":   {"urn:ietf:params:oauth:token-type:id_token"},
        "audience":             {strings.TrimRight(cfg.AuthServerURL, "/")},          // who must trust the ID-JAG
        "resource":             {strings.TrimRight(cfg.McpServerURL, "/")},           // the server the app ultimately wants to reach
        "client_id":            {cfg.ClientID},                                       // same client ID used for the OIDC login above
    }
    if cfg.Scope != "" {
        fields.Set("scope", cfg.Scope) // the scopes to request, from config.json
    }
    if cfg.ClientSecret != "" {
        fields.Set("client_secret", cfg.ClientSecret) // the client secret from config.json
    }

    return postForm(ctx, strings.TrimRight(cfg.IdpBaseURL, "/")+"/token", fields)
}

The scope and client_secret are only sent when they're set in config.json. If the IdP's policy allows it, it signs the ID-JAG and sends it back. That JWT is the app's ticket to the next server.

Try it: with the app still running from Step 1, click Analyze My Notes on the dashboard to run the flow again. Find the Step 2, Token Exchange (RFC 8693) entry. While it runs, the entry briefly shows the audience and resource being sent, which come from authServerUrl and mcpServerUrl in your config.json. When it finishes, it turns green and reads "ID-JAG assertion issued by IdP" with the time it took. The dashboard doesn't display the ID-JAG itself, only that the IdP issued one.

Exchange the ID-JAG for an access token with RFC 7523

An ID-JAG is useless against the MCP server directly. The resource's own authorization server, a different server than the one that just issued it, has to redeem the ID-JAG again.

In the same file, internal/xaa/tokenexchange.go, find requestAccessToken:

// internal/xaa/tokenexchange.go
func requestAccessToken(ctx context.Context, cfg config.XaaConfig, jag string) (string, error) {
    fields := url.Values{
        "grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"}, // RFC 7523's JWT bearer grant
        "assertion":  {jag},                                           // the ID-JAG from Step 2
        "client_id":  {cfg.McpClientID},                               // a different client ID than Step 2 used
    }
    if cfg.Scope != "" {
        fields.Set("scope", cfg.Scope) // the scopes to request, from config.json
    }
    if cfg.McpClientSecret != "" {
        fields.Set("client_secret", cfg.McpClientSecret) // the MCP client secret from config.json
    }

    endpoint := strings.TrimRight(cfg.AuthServerURL, "/") + "/token"
    return postForm(ctx, endpoint, fields)
}

Like the first exchange, it only sends scope and client_secret when they're set in config.json.

A third function chains both trades into one that the rest of the app calls. It's GetAccessToken, in the same file:

// internal/xaa/tokenexchange.go
func GetAccessToken(ctx context.Context, cfg config.XaaConfig, idToken string) (string, error) {
    jag, err := exchangeForJAG(ctx, cfg, idToken)
    if err != nil {
        return "", err
    }
    return requestAccessToken(ctx, cfg, jag)
}

Call GetAccessToken once, and an ID token walks out the other side as an access token good for one specific MCP server. The user never sees a second login or consent screen for any of it.

Try it: on the dashboard, find the Step 3, Access Token Request (RFC 7523) entry. When it finishes, it reads "Bearer token issued (aud: ...)". Below the step list, the Access Token box shows the first 50 characters of the token, and Token Claims shows its iss, aud, and sub. Check that aud matches the mcpServerUrl in your config.json. That means the resource server's authorization server accepted the ID-JAG and issued a token meant for this MCP server.

Call the MCP server with the access token

With that access token in hand, the app finally talks to the MCP server, using the official MCP Go SDK. The SDK's StreamableClientTransport has no built-in field for a bearer token, so AI Notes Assistant wraps the underlying http.Client in a small custom transport.

Open internal/mcpnotes/client.go. Find bearerTransport:

// internal/mcpnotes/client.go
type bearerTransport struct {
    token string
    base  http.RoundTripper
}

func (t *bearerTransport) RoundTrip(req *http.Request) (*http.Response, error) {
    req = req.Clone(req.Context())
    req.Header.Set("Authorization", "Bearer "+t.token) // attach the access token from Step 3
    base := t.base
    if base == nil {
        base = http.DefaultTransport
    }
    return base.RoundTrip(req)
}

With that transport in place, connecting and reading the data takes a few calls. Here they are in Fetch, in the same file:

// internal/mcpnotes/client.go
func Fetch(ctx context.Context, cfg config.XaaConfig, accessToken string) (*FetchResult, error) {
    httpClient := &http.Client{Transport: &bearerTransport{token: accessToken}} // accessToken is the Fetch parameter, from Step 3

    client := mcp.NewClient(&mcp.Implementation{Name: "oktane-go-mcp-xaa", Version: "1.0.0"}, nil)
    transport := &mcp.StreamableClientTransport{Endpoint: cfg.McpServerURL, HTTPClient: httpClient}

    session, err := client.Connect(ctx, transport, nil) // MCP handshake: protocol version + capabilities
    if err != nil {
        return nil, fmt.Errorf("connecting to MCP server: %w", err)
    }
    defer session.Close()

    resourceList, err := session.ListResources(ctx, &mcp.ListResourcesParams{}) // what the server offers
    if err != nil {
        return nil, fmt.Errorf("listing resources: %w", err)
    }
    resources := make([]string, 0, len(resourceList.Resources))
    for _, r := range resourceList.Resources {
        resources = append(resources, r.URI)
    }

    result, err := session.ReadResource(ctx, &mcp.ReadResourceParams{URI: cfg.ResourceURI}) // fetch the actual to-do data
    if err != nil {
        return nil, fmt.Errorf("reading resource %s: %w", cfg.ResourceURI, err)
    }

    var sb strings.Builder
    for _, c := range result.Contents {
        sb.WriteString(c.Text)
    }
    raw := sb.String()

    return &FetchResult{Resources: resources, Notes: parseTodosAsNotes(raw), RawContent: raw}, nil
}

If the access token is wrong, the failure shows up as an error from Connect or ReadResource, and the dashboard shows that message on Step 4. parseTodosAsNotes turns the raw to-do JSON into notes.

The XAA playground's resource server only speaks to-dos, not notes, so AI Notes Assistant reshapes each item into a note before it ever reaches the screen.

Try it: click Analyze My Notes once more and watch the dashboard stream every step live. Find the Step 4, MCP Server (Streamable HTTP) entry. When it finishes, it reads "N note(s) from MCP Server", where N is the number of to-do items returned from the todo0://todos resource in your config.json. Those items appear in the notes list, reshaped by parseTodosAsNotes. All four steps are checked off, and the notes come straight from the resource server. That's the real token exchange running against your Go MCP app, not a simulation. When you're done, stop the server with Ctrl+C.

Step 1 runs in HandleLogin and HandleCallback when you click Sign in. Steps 2 through 4 run inside one handler, FlowHandler, which the dashboard calls as soon as you're signed in and again whenever you click Analyze My Notes; it calls GetAccessToken and then Fetch, and streams each step to the dashboard. From the browser it looks like a single click, and the token exchanges happen in between without any extra prompt.

Learn more about secure AI agent development with Go and MCP

One login, two token trades most users never notice, and a working connection to a server that had no reason to trust this app a second earlier. That's the experience more organizations are adopting XAA to deliver.

A few places to keep exploring:

XAA is an open standard, the parts that matter here are the token exchange and the policy check, solid enough to build on today. If you're wiring an AI agent to reach past your own app's boundary, this is worth trying before you fall back to a shared API key.

Remember to follow us on X and subscribe to our YouTube channel for more exciting content. We also want to hear from you about the topics you'd like to see and any questions you may have. Leave us a comment below!

Vanshika is a Senior Builder Advocate at Okta passionate about Tech, AI, and community engagement. She connects with 600k+ developers across tech communities worldwide sparking conversations and inspiring innovation. Off the clock, she's either on the pickleball court or deep in her latest gaming session.

Okta Developer Blog Comment Policy

We welcome relevant and respectful comments. Off-topic comments may be removed.