Cloud Explainers

How to Fix OAuth 'invalid_grant' Errors

Auth (OAuth, JWT)9 min video

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.

The password worked. The swap didn't.: diagram of Jen signs in, John's server

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.

Sign in, get a code, swap it for tokens: diagram of Jen's browser, Shuttle ID, John's app

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.

John's app server
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.

John's app server
signinJen signed in. Sent back to https://shuttle.test/callback
code: a016afab-2d0... (saved in ~/flow/code)
John's app server
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.

A valet ticket, and a code: cards of Good once, For a short time, At the same stand, Halves must match

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.

Four checks on every code: diagram of John's app, Shuttle ID, Used before?, Too old?, Same address?, Verifier matches?, the four checks

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.

John's app server
exchange200 OK  access_token: eyJhbGciOi... (expires in 300 s)
        refresh_token: eyJhbGciOi... (saved in ~/flow/refresh)
John's app server
exchange400 {"error":"invalid_grant","error_description":"Code not valid"}
John's app server
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 used twice: browser screenshot from the video

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.

John's app server
signinJen signed in. Sent back to https://shuttle.test/callback
code: 126bcf60-f96... (saved in ~/flow/code)
John's app server
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.

John's app server
REDIRECT_URI=https://shuttle.test/callback/ exchange400 {"error":"invalid_grant","error_description":"Incorrect redirect_uri"}
John's app server
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.

One address for both steps: code change of shuttle.env, REDIRECT_URI=https://shuttle.test/callback (same as sign-in)

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.

John's app server
signinJen signed in. Sent back to https://shuttle.test/callback
code: 42ae6173-2fe... (saved in ~/flow/code)
John's app server
CODE=$(cat ~/flow/first) exchange400 {"error":"invalid_grant","error_description":"PKCE verification failed: Code mismatch"}
John's app server
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.

John's app server
signinJen signed in. Sent back to https://shuttle.test/callback
code: b3830c90-409... (saved in ~/flow/code)
John's app server
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.

John's app server
refresh200 OK  new access_token: eyJhbGciOi... (expires in 300 s)
        new refresh_token: eyJhbGciOi... (saved in ~/flow/refresh)
John's app server
signout204 signed out
John's app server
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.

John's app server
refresh200 OK  new access_token: eyJhbGciOi... (expires in 300 s)
        new refresh_token: eyJhbGciOi... (saved in ~/flow/refresh)
John's app server
TOKEN=$(cat ~/flow/old) refresh400 {"error":"invalid_grant","error_description":"Maximum allowed refresh token reuse exceeded"}
John's app server
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.

Refresh tokens: signed out or reused: browser screenshot from the video

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.

Read the error_description: cards of Code not valid, Incorrect redirect_uri, PKCE or client_id, Refresh refused

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

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.

More videos

PostgreSQL9 min

Every PostgreSQL Setting to Change After You Install It

Docker9 min

What Happens When You Install Docker on Ubuntu

Python8 min

How to Fix Python 'Address Already in Use' Errors

Go (Golang)5 min

Golang Interfaces and Mocks in 5 Minutes

Git7 min

How to Fix Git 'Detached HEAD' State

Linux21 min

Linux Firewall with ufw: Full Tutorial for Beginners

Go (Golang)5 min

Golang defer Statements in 5 Minutes

Databases & SQL11 min

The SQL Roadmap for Beginners

Go (Golang)5 min

Golang make() for Slices and Maps in 5 Minutes

Networking7 min

How to Fix Network 'No Route to Host' Errors on Linux

Linux6 min

How to Fix Linux 'Too Many Open Files' Errors

Django (Python web framework)11 min

Every Django Concept a Beginner Needs to Know

Linux24 min

SSH on Linux: Full Tutorial for Beginners

Go (Golang)5 min

Golang for range Loops in 5 Minutes

Databases & SQL10 min

SQL Databases: SQLite vs PostgreSQL

Django (Python web framework)10 min

The Django Roadmap for Beginners

Go (Golang)5 min

Golang Structs in 5 Minutes

Caching & Redis22 min

Redis: Full Tutorial for Beginners

Go (Golang)5 min

Golang context.Context in 5 Minutes

Databases & SQL7 min

How to Fix MySQL Database Error 1045: Access Denied for User

Go (Golang)5 min

Golang Method Receivers in 5 Minutes

Python8 min

How to Fix Python SSL: CERTIFICATE_VERIFY_FAILED Errors

Django (Python web framework)9 min

How to Fix Django Static Files Not Loading in Production

OpenRouter (one API for many AI models)8 min

OpenRouter vs Direct API Keys: Which One Should You Use?

Go (Golang)5 min

Golang if err != nil Checks in 5 Minutes

Go (Golang)8 min

How to Fix Golang 'go.mod File Not Found' Errors

AI agents & MCP22 min

MCP Servers: Full Tutorial for Beginners

Go (Golang)5 min

Golang Error Return Values in 5 Minutes

Python8 min

How to Fix Python ModuleNotFoundError: No Module Named

Go (Golang)5 min

Golang Pointers in 5 Minutes

Kubernetes8 min

How to Fix a Kubernetes Pod Stuck in CrashLoopBackOff

Homelab & self-hosting9 min

How to Fix a Homelab ESXi Host Not Responding

PostgreSQL24 min

PostgreSQL: Full Tutorial for Beginners

Load balancing & Nginx9 min

How a Load Balancer Works with HAProxy

Python9 min

How Python Virtual Environments Work

Homelab & self-hosting9 min

How to Fix Cloudflare Tunnel Errors in a Homelab

APIs9 min

How to Fix API CORS Errors: No 'Access-Control-Allow-Origin'

Auth (OAuth, JWT)9 min

How Authenticator App Login Codes Work (TOTP)

Git22 min

Git and GitHub: Full Tutorial for Beginners

Homelab & self-hosting10 min

How a Homelab Hypervisor Works (VMware ESXi)

Kubernetes9 min

How to Fix Kubernetes ImagePullBackOff Errors

DNS8 min

How to Fix DNS 'Temporary Failure in Name Resolution' on Linux

AWS8 min

How to Fix AWS CLI 'Unable to Locate Credentials'

Homelab & self-hosting10 min

Proxmox vs ESXi for Your Homelab: When Each One Wins

PostgreSQL10 min

PostgreSQL UUID vs Auto Increment: Which Primary Key Should You Use?

Kubernetes21 min

Kubernetes: Full Tutorial for Beginners

Networking9 min

How TCP Sockets Work

PostgreSQL7 min

How to Fix PostgreSQL 'Could Not Connect to Server'

Claude & the Claude Developer Platform9 min

Claude Code Hooks Will Finally Make Sense After This

DevOps & CI/CD9 min

DevOps with Ansible Will Finally Make Sense After This

Networking9 min

How SNMP Network Monitoring Works

Git8 min

How to Fix GitHub 'Permission Denied (publickey)' Errors

Docker21 min

Docker: Full Tutorial for Beginners

PostgreSQL7 min

How to Fix PostgreSQL 'Password Authentication Failed'

Linux8 min

Why One Linux Server Handles More Users Than You Think

Networking7 min

How to Fix Network 'Connection Refused' Errors

DevOps & CI/CD9 min

DevOps Pipelines: Jenkins vs GitHub Actions

Linux11 min

Linux Nginx Reverse Proxy: Full Tutorial for Beginners

Networking11 min

Every Networking Term a Beginner Needs in 12 Minutes

Docker6 min

How to Fix Docker 'Permission Denied' on docker.sock

Git7 min

How to Fix Git 'Updates Were Rejected' When You Push

Linux7 min

How to Fix nginx 502 Bad Gateway Errors on Linux

Linux8 min

How to Fix Linux apt 'Could Not Get Lock' Errors (Ubuntu)

Networking9 min

How Email Works on the Internet (SMTP) in 10 Minutes

Python8 min

The Python Roadmap for Beginners

Go (Golang)21 min

Golang REST API with Gin: Full Tutorial for Beginners

Networking10 min

How a WireGuard VPN Network Works

Linux9 min

Linux Makefiles Will Finally Make Sense After This

Auth (OAuth, JWT)9 min

SAML vs OAuth vs OpenID Connect: What's the Difference?

Python7 min

How to Fix Python cron Jobs That Never Run

Linux22 min

Linux Bash Scripting: Full Tutorial for Beginners

Networking10 min

How PXE Network Boot Works

Active Directory9 min

How Active Directory Works

Linux10 min

How to Fix a Linux systemd Service That Won't Start

Linux9 min

Linux Logs: syslog vs journald

Auth (OAuth, JWT)9 min

JWT vs Session Cookies: Which One Should You Use?

Docker10 min

Docker vs Docker Compose: Which One Should You Use?

Docker9 min

How to Fix Docker Compose Containers That Can't Talk to Each Other

Django (Python web framework)22 min

Django Full Tutorial for Beginners

Linux9 min

How Linux systemd Works

Networking8 min

How to Fix 'Windows Cannot Access' Network Share Errors (SMB)

APIs10 min

REST vs gRPC: Which One Should You Use?

Certificates & PKI (ADCS)9 min

How to Fix SSL Certificate Chain Errors (Missing Intermediate)

Python9 min

Every Python Concept for Beginners in 10 Minutes

Databases & SQL9 min

Every SQL Join Type in 10 Minutes

OpenRouter (one API for many AI models)9 min

Why OpenRouter Free Models Hit Their Limit So Fast

Gemini API & Google AI Studio9 min

Why Your Gemini API Free Tier Runs Out So Fast

OpenRouter (one API for many AI models)10 min

OpenRouter Will Finally Make Sense After This

Caching & Redis10 min

How Redis Caching Works

Gemini API & Google AI Studio10 min

Gemini API vs Vertex AI: Which One Should You Use?

Gemini API & Google AI Studio8 min

How to Fix a Leaked Gemini API Key

Go (Golang)9 min

Why Golang Uses Goroutines Instead of Threads

Gemini API & Google AI Studio9 min

How to Fix Gemini API Error 429: Resource Exhausted

Claude & the Claude Developer Platform10 min

Claude Token Pricing Will Finally Make Sense After This

Python11 min

Why Python Web Scraping Returns Nothing (and the Fix)

Python10 min

Python uv vs pip: Which One Should You Use?

Python22 min

Python Automation: Full Tutorial for Beginners

Auth (OAuth, JWT)9 min

How OAuth Login Works

Gemini API & Google AI Studio10 min

Google AI Studio Will Finally Make Sense After This

Docker10 min

What Happens When You Run a Docker Container

Claude & the Claude Developer Platform8 min

How to Fix Claude Code Billing Your API Key Instead of Your Plan

Auth (OAuth, JWT)9 min

Why Passkeys Can't Be Phished Like Passwords

PowerShell10 min

PowerShell vs Bash: Which One Should You Learn?

Linux10 min

The Linux Roadmap for Beginners

Django (Python web framework)9 min

Django vs FastAPI: Which One Should You Use?

Databases & SQL10 min

Why SQLite Is the Most Used Database in the World

Databases & SQL11 min

How a NoSQL Database Like MongoDB Works

Python11 min

How to Fix Python pip error: externally-managed-environment

Databases & SQL9 min

How to Fix MySQL Too Many Connections Database Errors

Go (Golang)9 min

Golang Concurrency Will Finally Make Sense After This

AWS10 min

How Amazon S3 Works

Kubernetes10 min

How Kubernetes Works

Git10 min

How Git Works

Docker10 min

How to Fix Docker Port Already Allocated Errors

PostgreSQL10 min

How PostgreSQL Works

Git8 min

How to Fix Git Merge Conflicts

Linux9 min

How to Fix No Space Left on Device in Linux

Networking10 min

How the Internet Works

Databases & SQL9 min

SQL vs NoSQL: When Each One Wins

Auth (OAuth, JWT)8 min

How to Fix JWT Token Expired Errors (401 Unauthorized)

Claude & the Claude Developer Platform9 min

Claude API vs Claude Pro: Why Your Subscription Doesn't Include It

AI agent skills9 min

Why AI Agent Skills Beat Giant Prompts

Linux10 min

Linux Cron Jobs Will Finally Make Sense After This

Cybersecurity10 min

Security Logs Will Finally Make Sense After This

Cybersecurity8 min

How to Fix a Security Leak: An API Key Pushed to GitHub

DNS9 min

DNS Will Finally Make Sense After This

Cybersecurity9 min

Never Ignore a Security Update

Auth (OAuth, JWT)9 min

Two-Factor Authentication Will Finally Make Sense

Networking8 min

Never Expose a Database to the Internet

Cybersecurity10 min

SSH Keys vs Passwords: Which Is Safer for Security?

Linux10 min

The 5 Levels of Linux Boot: From Power On to Login

Networking12 min

The 5 Levels of Network Firewalls

Cybersecurity10 min

Password Security: Why Hackers Crack Weak Passwords

Linux9 min

Why Your Linux Server Runs Out of Memory

Networking10 min

HTTP vs HTTPS: What Actually Changes on Your Network

Linux12 min

Every Linux File Permission You Need to Know

Linux10 min

Linux Processes vs Threads: When Each One Wins

Networking11 min

The OSI Model Will Finally Make Sense After This

Git11 min

The 7 Levels of Git

Networking10 min

Every Network Troubleshooting Command You Need

Cybersecurity10 min

Hashing vs Encryption in Cybersecurity: When Each One Wins

Networking11 min

Why the Internet Ran Out of IP Addresses

Linux11 min

Linux Package Managers: apt vs Snap vs Flatpak

Python9 min

Why Python Is Slow (and When It Doesn't Matter)

Networking11 min

TCP vs UDP: When Each One Wins

Linux8 min

Stop Running Linux as Root (Do This Instead)

Linux11 min

Linux Users and Groups Will Finally Make Sense

Cybersecurity9 min

Why Phishing Beats Good Security (and How to Spot It)

Docker12 min

The 7 Levels of Docker

AI agents & MCP12 min

AI Agents Will Finally Make Sense After This

Git8 min

Stop Using git push --force (Use This Instead)

AI agent skills10 min

Agent Skills vs MCP: When Each One Wins

Networking12 min

Networking Will Finally Make Sense After This

Linux12 min

Every Linux Command You Actually Need

Cybersecurity12 min

The 7 Levels of Cybersecurity

System design12 min

Every System Design Concept You Need, in One Diagram

PostgreSQL10 min

Why PostgreSQL Ignores Your Index