How to Fix OAuth 'invalid_grant' Errors
How to fix OAuth invalid_grant errors, for beginners, on a real sign-in service (Keycloak): why a wrong client secret gives a different error, the four checks on every authorization code (used twice, too old, a different redirect URI, a PKCE verifier from another sign-in), and why refresh tokens fail after a sign-out or when an old one is reused.
Not a wrong secret
Your app's sign-in fails with invalid_grant, even though the password was right. John runs the booking app for an airport shuttle, and his rider Jen signs in fine. Then his server asks for her tokens, and gets this: 400, invalid_grant, Code not valid. There are a handful of usual causes, and one line of the error tells you which. Two of them even end a sign-in that was already working.

Here's the trade. Jen doesn't type her password into John's app. She signs in at Shuttle ID, the shuttle company's sign-in service. It sends her browser back to John's app with a short, one-time code in the address. John's server then sends that code back to Shuttle ID, and swaps it for tokens: the passes that let the app act for Jen. invalid_grant means Shuttle ID refused that swap.

Most people guess the app's secret is wrong, the password the app itself uses with the sign-in service. John's exchange script sends the same request his server sends, but with a wrong secret on purpose. That's a different answer: 401, unauthorized_client. So invalid_grant isn't about the app. It's about the one-time code the app traded in.
SECRET=not-the-secret exchange401 {"error":"unauthorized_client","error_description":"Invalid client or Invalid client credentials"}
So the usual fix is to get a fresh code. Send Jen through sign-in again, and swap the new code once, right away. 200, tokens. But if the bug is still there, the next sign-in fails the same way. The real fix is to find out why Shuttle ID refused, and the error_description tells you.
signinJen signed in. Sent back to https://shuttle.test/callback code: a016afab-2d0... (saved in ~/flow/code)
exchange200 OK access_token: eyJhbGciOi... (expires in 300 s) refresh_token: eyJhbGciOi... (saved in ~/flow/refresh)
Think of a valet ticket at the airport. It gets your car back once. Only for a short time, only at the stand where you left the car, and only with the stub you kept matching the half the valet kept. The code works the same way.

When John's server sends the code, Shuttle ID checks four things. Has this code been used before? Is it too old? Does the redirect address, where Shuttle ID sent Jen back to, match the one from sign-in? And does the verifier match? That's a secret the app made at sign-in, its half of the stub. This check is called PKCE. If any check fails, the answer is invalid_grant.

A code used twice
Why was Jen's code not valid? It had already been swapped. John's callback page, the page Shuttle ID sends riders back to, ran twice: Jen hit reload, and the page sent the same code again. A double click, or an app that retries a failed request, does the same. The first swap got tokens. The second got Code not valid. Guess first: does Jen's first sign-in still work? No. John asks Shuttle ID to renew the tokens from that first swap, and it says Jen's sign-in is gone: Session doesn't have required client.
exchange200 OK access_token: eyJhbGciOi... (expires in 300 s) refresh_token: eyJhbGciOi... (saved in ~/flow/refresh)
exchange400 {"error":"invalid_grant","error_description":"Code not valid"}
refresh400 {"error":"invalid_grant","error_description":"Session doesn't have required client"}
That's the OAuth standard doing its job. RFC 6749 says a code must not be used more than once, and when it is, the server should revoke every token that code gave out, in case someone stole it. The fix: swap each code exactly once, and make a reloaded callback page sign the rider in again, not resend the code.

A code too old
The same words, Code not valid, also mean the code is too old. John signs Jen in, waits 61 seconds, then swaps. Refused. This bites when a code is copied by hand into a test tool, or the server stops at a breakpoint while you debug, or a slow request sits in a queue. The standard says codes must expire shortly, ten minutes at the most, and many services use far less. Shuttle ID runs on Keycloak, a popular sign-in server, and its default is just one minute. So swap the code the moment it arrives.
signinJen signed in. Sent back to https://shuttle.test/callback code: 126bcf60-f96... (saved in ~/flow/code)
sleep 61; exchange400 {"error":"invalid_grant","error_description":"Code not valid"}
A different redirect address
Next, a code that's fresh and used once, and still refused. At sign-in, John's app said: send Jen back to shuttle dot test, slash callback. Shuttle ID checks that the swap uses that same address, so a code can't be cashed in by a page that never started the sign-in. At the swap, a config file has one extra slash at the end. Incorrect redirect_uri. Then he fixes it and tries the same code again: Code not valid. One bad try used it up.
REDIRECT_URI=https://shuttle.test/callback/ exchange400 {"error":"invalid_grant","error_description":"Incorrect redirect_uri"}
exchange400 {"error":"invalid_grant","error_description":"Code not valid"}
The fix is one character. The swap has to send exactly the address from sign-in, with every slash, the same http or https, and the same port. The http or https part bites apps behind a load balancer, a front server that takes https from the rider and passes plain http on. Keep the address in one setting both steps read.

A verifier from another sign-in
Now the sneaky one. The code is fresh, used once, the address matches, and it's still refused. At each sign-in, John's app makes a secret, random string, the verifier. It sends Shuttle ID only a scrambled form of it. At the swap, it must send the verifier itself. Now say Jen opens two tabs and starts sign-in twice. John's app keeps only one verifier at a time, so the second sign-in replaces the first one's. John recreates that: a second sign-in, then he swaps the first sign-in's code. PKCE verification failed: Code mismatch. And if the verifier is lost completely, the answer is: PKCE code verifier not specified. The fix uses a tag every sign-in already carries, called state, which comes back with the code. Save each verifier under its state, not in one shared slot.
signinJen signed in. Sent back to https://shuttle.test/callback code: 42ae6173-2fe... (saved in ~/flow/code)
CODE=$(cat ~/flow/first) exchange400 {"error":"invalid_grant","error_description":"PKCE verification failed: Code mismatch"}
VERIFIER= exchange400 {"error":"invalid_grant","error_description":"PKCE code verifier not specified"}
A code for another app
What if the code is fine, but the wrong app swaps it? John's company has a second app, the dispatch desk, with its own client ID and secret. Both apps run on one server. One setting gets mixed up, and the booking app's code is sent with the desk's ID. Refused: Found different client_id. A code belongs to the app that asked for it, so check that both steps use the same client ID.
signinJen signed in. Sent back to https://shuttle.test/callback code: b3830c90-409... (saved in ~/flow/code)
CLIENT=dispatch-desk SECRET=$(cat ~/.desk-secret) exchange400 {"error":"invalid_grant","error_description":"Auth error: Found different client_id in clientSession"}
Refresh tokens: signed out or reused
Now the other kind of invalid_grant: Jen was signed in fine, and later the app suddenly can't act for her. At sign-in, the app got an access token, the pass it shows on every request, good here for five minutes, plus a refresh token that gets new passes without asking Jen again. It works, until Jen taps sign out, which John's app passes on to Shuttle ID. Then the same request gets: Session not active. Her sign-in is over, so the token went with it. The same happens when an admin ends her session, or the token sits unused too long. And if your app uses Google's sign-in and is still in testing mode, Google ends its refresh tokens after seven days.
refresh200 OK new access_token: eyJhbGciOi... (expires in 300 s) new refresh_token: eyJhbGciOi... (saved in ~/flow/refresh)
signout204 signed out
refresh400 {"error":"invalid_grant","error_description":"Session not active"}
Some services hand back a brand-new refresh token on every refresh, and the old one stops working. That's called rotation. John's app saved the new one, but an old copy got sent again. Maximum allowed refresh token reuse exceeded. Like the reused code earlier, this ends a sign-in that was working. Shuttle ID treats a reused token as a sign it may have been stolen, so it ends the whole session: the newest token fails too. Save every new refresh token. And when a refresh gets invalid_grant, don't retry, because the same token will fail again. Send the user to sign in again.
refresh200 OK new access_token: eyJhbGciOi... (expires in 300 s) new refresh_token: eyJhbGciOi... (saved in ~/flow/refresh)
TOKEN=$(cat ~/flow/old) refresh400 {"error":"invalid_grant","error_description":"Maximum allowed refresh token reuse exceeded"}
refresh400 {"error":"invalid_grant","error_description":"Session doesn't have required client"}
The OAuth 2.0 standard, RFC 6749, defines invalid_grant with exactly this list: invalid, expired, revoked, the wrong redirect address, or issued to another app. One error, many causes. So log the whole error, including its description, and the next one takes a minute to find.

Recap
Code not valid: used twice, or too old. Incorrect redirect_uri: match the address exactly. PKCE: each sign-in's own verifier. Client ID: the same app for both steps. And a refused refresh: sign in again.

If this got your sign-in working, subscribing brings the next fix in plain words.
All the lab files and commands are linked in the description. Thanks for watching Cloud Explainers.
Sources
- RFC 6749, The OAuth 2.0 Authorization Framework, 4.1.2 Authorization Response
- RFC 6749, 4.1.3 Access Token Request (redirect_uri must be identical)
- RFC 6749, 5.2 Error Response (invalid_grant)
- RFC 7636, Proof Key for Code Exchange (PKCE)
- Keycloak Server Administration Guide, session and token timeouts, Revoke Refresh Token
- Google, Using OAuth 2.0 to Access Google APIs, Refresh token expiration
Demos: two containers on our own Mac, a stock Keycloak and a stock Ubuntu app server; the shuttle company, its app and its rider are made up. Every command, output and error was real. Watch the full video on YouTube.