2085 words
10 minutes
Logging In with Workday: OAuth, PKCE, and Where JWTs Fit
2026-12-05
No Tags

OAuth 2.0 · PKCE · Workday Extend

I have a side project called The Intersect. It helps you find movies, TV shows and board games by stacking filters on top of each other, and it was already set up to let people log in with their TMDB account. I decided I wanted a “Login with Workday” button for a demo. How hard could it be? It’s OAuth. I’ve been doing OAuth for a Very. Long. Time.

I mean, what could go wrong?

Turns out there were a few speed bumps.

None of them were big, and every one of them makes sense in hindsight. But this is exactly the kind of thing I like to write down, so you can drive around the potholes I found with my face. Here’s the story of how the login works, what PKCE is doing in there, and where JWTs do (and don’t) belong.

  1. Browser: makes a verifier, sends its hash (code_challenge)
  2. Workday: signs the user in, sends a code back (#code=…&state=…)
  3. My function: trades code and verifier for tokens (code_verifier)
  4. Workday API: says who the user is (workers/me)

The cast of characters#

The Intersect is plain JavaScript in the browser with a few Netlify Functions behind it. No framework, no auth library. That turns out to be great for learning, because every step of the dance is right there in the code where you can see it.

Before writing any code you need three things from the Workday Developer Site:

  • An API client. Under Console, choose API Clients, then Create API Client. You give it a name, a redirect URI, your CORS domains (just the base URL for your application server) and the scopes you need. Workday gives you back a client ID and a client secret.
  • Your redirect URI, exactly. I registered both https://theintersect.netlify.app and http://localhost:8888 so I could test locally. The value your app sends has to match what you registered, character for character. A trailing slash counts.
  • Your region’s base URLs. Your account lives in one region, and using the wrong region’s gateway gets you a 401. Mine is the US one: https://api.us.wcp.workday.com for the APIs and https://api.us.wcp.workday.com/auth for authorization. Yours is on your profile in the Developer Site.

The client secret goes in a server-side environment variable and never, ever, ever goes to the browser. (You knew that. I’m saying it anyway.)

The dance, in four steps#

  1. The browser makes up a secret, and sends the user to Workday with a hash of that secret.
  2. The user signs in, and Workday sends them back to my app with a one-time code.
  3. My server trades the code, plus the original secret, for tokens.
  4. My server uses the access token to ask Workday who this person is.

Steps 1 and 3 are where PKCE lives, so let’s talk about that.

PKCE: a secret handshake with yourself#

PKCE (people say “pixie”, which is delightful) stands for Proof Key for Code Exchange. The problem it solves is simple. That one-time code in step 2 travels through the browser’s address bar, and things in address bars get seen: by extensions, by logs, by history. If someone grabs the code, can they trade it for tokens?

With PKCE, no. Before the user leaves, your app invents a random string called the code verifier. It sends Workday only the SHA-256 hash of it, called the code challenge. Later, when it trades in the code, it has to show the original verifier. Workday hashes it, compares, and only hands over tokens if they match. A stolen code is useless without the verifier, and the verifier never went anywhere near the address bar.

Here’s the browser side:

// 32 random bytes as hex = 64 characters (Workday wants 43 to 128)
const codeVerifier = Array.from(crypto.getRandomValues(new Uint8Array(32)))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
// The challenge is the base64url-encoded SHA-256 hash of the verifier
const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(codeVerifier));
const codeChallenge = btoa(String.fromCharCode(...new Uint8Array(hash)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
// A second random value so we can tell this response is really ours
const state = Array.from(crypto.getRandomValues(new Uint8Array(16)))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
sessionStorage.setItem('workday_oauth_state', state);
sessionStorage.setItem('workday_oauth_verifier', codeVerifier);
const params = new URLSearchParams({
response_type: 'code',
client_id: config.clientId,
redirect_uri: window.location.origin,
state,
code_challenge: codeChallenge,
code_challenge_method: 'S256'
});
if (config.tenantAlias) params.set('tenantAlias', config.tenantAlias);
window.location.href = `${config.authBaseUrl}/v1/authorize?${params}`;

Two things to point out. The state value is a separate protection: when the user comes back, I check that the state in the URL matches the one I stored, which tells me this response belongs to a login I actually started. And tenantAlias is optional, but without it Workday shows the user an extra page asking which tenant they want. Sending it skips that page.

Now, my confession. My first pass at this sent the challenge and never sent the verifier. I did the hard cryptography part, carefully stored the verifier in sessionStorage… and then left it sitting there like a packed lunch on the kitchen counter. Workday’s docs are clear about what happens next: no matching verifier, invalid_grant, no tokens. If you tell the server you’re doing PKCE, you have to finish doing PKCE.

Coming back with the code#

Here’s a speed bump that got me. Most OAuth providers send the code back in the query string, like ?code=abc. Workday’s documentation shows it coming back in the URL fragment:

https://example.com/#code=88xr1xk2snm6u6pk5yc6yqef0&state=xyz

That little # matters a lot. Browsers never send the fragment to the server, so your backend can’t see it. Your front-end JavaScript has to pick the code up and hand it over. My callback checks both places, because I am a belt and suspenders kind of person:

const query = new URLSearchParams(window.location.search);
const params = (query.has('code') || query.has('error'))
? query
: new URLSearchParams(window.location.hash.substring(1));
const code = params.get('code');
const storedState = sessionStorage.getItem('workday_oauth_state');
const codeVerifier = sessionStorage.getItem('workday_oauth_verifier');
// One use only: clear them whatever happens next
sessionStorage.removeItem('workday_oauth_state');
sessionStorage.removeItem('workday_oauth_verifier');
if (params.get('state') !== storedState) {
throw new Error('State mismatch');
}
const response = await fetch('/.netlify/functions/workday_auth?action=token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
code,
redirect_uri: window.location.origin,
code_verifier: codeVerifier // the packed lunch, finally
})
});

Trading the code for tokens#

This part happens in a Netlify Function, because it needs the client secret. Workday’s PKCE guide is written for public clients, where the app has no safe place to keep a secret. I do have a server, so I use both: PKCE protects the code on its trip through the browser, and the secret proves the request is coming from my backend.

async function requestToken(params) {
const auth = Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64');
const body = new URLSearchParams({ ...params, client_id: CLIENT_ID }).toString();
let response;
for (const scheme of ['ID', 'Basic']) {
response = await fetch(`${WORKDAY_AUTH}/v1/token`, {
method: 'POST',
headers: {
'Authorization': `${scheme} ${auth}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
body
});
if (response.ok) return { statusCode: 200, body: JSON.stringify(await response.json()) };
}
// ...report the error
}
// Called with:
requestToken({
grant_type: 'authorization_code',
code,
redirect_uri: redirectUri,
code_verifier: codeVerifier
});

Ok, and yes, you’re looking at that loop and wondering what on earth ID is. Workday’s docs describe the Authorization header as ID followed by your base64-encoded credentials. Some of the examples on those same pages say Basic, which is what the rest of the OAuth world uses. Rather than argue with the documentation, my function tries one and then the other. It’s not elegant. It works.

One more small thing: build that request body with URLSearchParams, not by gluing strings together. Codes and redirect URIs have characters that need encoding, and “it worked with my test values” is how you end up debugging at midnight.

What comes back looks like this:

{
"access_token": "7c3obrknwd6nnkxv0r64jdpbx",
"refresh_token": "yxsiqvdkakj0tp9a4i2xe1fbg...",
"token_type": "Bearer"
}

So… who are you?#

I have a token. I still don’t know who logged in. The token is just a key, so I use it to ask:

const response = await fetch(`${WORKDAY_GATEWAY}/common/v1/workers/me`, {
headers: { 'Authorization': `Bearer ${accessToken}` }
});

And here was my next speed bump. I’d assumed the response would have firstName and lastName. It doesn’t. Workday puts the display name in a field called descriptor, so my lovely logout button was all set to greet everyone as “Workday User”. Once I read descriptor, I got what I wanted: a button that says Logout Logan McNeil. (If you’ve spent any time in a Workday demo tenant, you and Logan are old friends.)

Refresh tokens: use it and lose it#

The access token doesn’t last forever. Its lifetime is tied to the session timeout your Workday administrator set, and the docs put it at 60 minutes for Extend APIs. When it runs out, you trade the refresh token for a new access token with grant_type=refresh_token.

The catch: every refresh gives you a new refresh token, and you need to use the new one next time. My first version saved the new access token and kept the old refresh token. That works exactly once. Save both, every time.

Also worth knowing: the overall refresh window is set when you register the client, the clock starts at the first login, and refreshing doesn’t extend it. When it’s up, the user signs in again.

Where do JWTs come in?#

This question comes up a lot, because for many people “OAuth” and “JWT” have fused into one word. They’re different things, so let’s untangle them.

The Workday tokens in this flow aren’t something you should read. Look at that token response again. No id_token. The examples in Workday’s docs are short random-looking strings. This is OAuth, which is about access, and not OpenID Connect, which adds an identity token on top. Treat the access token as an opaque key. Don’t decode it, don’t parse it, don’t build anything that depends on what’s inside. If you want to know who the user is, ask the API, which is what the workers/me call is for.

A JWT is a great fit for your own app’s session. Here’s where I’d take it next. Once Workday has vouched for the user, my app needs to remember that. Right now the browser holds on to a user ID and sends it along with each request, which means my API is taking the browser’s word for who it’s talking to. For a demo, fine. For real life, no. The better pattern is for my server to issue its own signed token after the workers/me call succeeds:

import { SignJWT, jwtVerify } from 'jose';
const secret = new TextEncoder().encode(process.env.SESSION_SECRET);
// After workers/me succeeds:
const session = await new SignJWT({ name: worker.descriptor })
.setProtectedHeader({ alg: 'HS256' })
.setSubject(`workday_${worker.id}`)
.setIssuedAt()
.setExpirationTime('1h')
.sign(secret);
// On every API request:
const { payload } = await jwtVerify(session, secret);
// payload.sub is who they are, and nobody can fake it without the secret

That’s a sketch and not what’s running in The Intersect today, but it’s the right shape. The JWT is mine: I sign it, I verify it, and the Workday tokens can stay on the server where they belong. (Today mine live in the browser’s localStorage. Demo-ware. Don’t copy that part.)

Workday does use JWTs for a different job. If you’re building a server-to-server integration with no human logging in, Workday has a JWT bearer grant, where your service signs a JWT with its own key and trades it for an access token. Different flow, different setup, same word. If someone tells you “Workday uses JWTs for auth”, this is usually what they mean.

The speed bumps, all in one place#

  • Finish the PKCE handshake. Sending a challenge commits you to sending the verifier.
  • Look for the code after the #. And remember your server can’t see it.
  • ID or Basic? The docs show both. Be ready for either.
  • The name is in descriptor. Not firstName and lastName.
  • Refresh tokens rotate. Store the new one every single time.
  • Send tenantAlias if you want to skip the “which tenant?” page.
  • Don’t forget logout. I wired up the whole login and then discovered my logout button only knew about TMDB. Clear the Workday tokens too.
  • The redirect URI must match exactly. Every time, on every provider, forever.

So, in summary#

Logging in with Workday is standard OAuth with a few local customs. PKCE is a handshake your app does with itself so a stolen code is worthless. The tokens Workday gives you are keys, and you ask the API who’s holding them. JWTs are a lovely tool for your own sessions and a separate Workday feature for service integrations, and neither of those is the login flow itself.

And if you get stuck? Open the network tab, look at exactly what you sent, and compare it to the docs one parameter at a time. That’s how you find the packed lunch.

Go build something. I’d love to hear what you make.

Further reading#