Tutorial

How to Implement OAuth2 Auth Code for a Server App

Implement the OAuth 2.0 authorization code flow for a server-side app so the client secret stays on the server and tokens never reach the browser.

On this page

  1. Introduction
  2. Redirect to authorize
  3. Receive the code
  4. Exchange for tokens
  5. Store in session
  6. Refresh server-side
  7. Test the flow
  8. Common pitfalls
  9. Conclusion

Introduction

The hardest part of secure server OAuth is not writing the code — it is deciding what the code is allowed to reject. A auth code flow setup that accepts everything is easy to ship and expensive to operate, because every malformed input becomes a production surprise. The discipline is to enumerate the shapes the system actually receives, encode them in auth code flow, and let the library reject the rest loudly. This keeps the happy path fast and the failure path visible.

A auth code flow guard for secure server OAuth should be proportional to the risk. A ten-field form does not need a hundred-line schema; it needs the five checks that catch the five mistakes the users actually make. Ship the five, measure the rejections, and add the sixth only when the traffic proves it exists. Speculative generality is the bug you write on purpose, and auth code flow makes it easy to write, which is why discipline matters.

The sections below walk through the concrete decisions: where to put the auth code flow check, how to keep it fast under load, what to do when the contract changes, and how to test the failure paths so they degrade on purpose instead of by accident.

Redirect to authorize

Redirect to authorize is the first decision because it determines what the rest of the auth code flow pipeline can assume. A wrong choice here turns into secure server OAuth under load, and the invariant you thought auth code flow guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.

The test for Redirect to authorize is the one most teams skip: drive auth code flow to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.

app.get('/callback', async (req, res) => {
  const { access_token } = await exchange(req.query.code, CLIENT_SECRET);
  req.session.token = access_token;
  res.redirect('/');
});

The javascript above is the shape to ship for secure server OAuth. It is small enough to audit and specific enough that the failure behavior is obvious. Adapt the constants to your traffic and latency budget, and resist the urge to handle cases the system has not seen yet.

Receive the code

The mechanism behind Receive the code is straightforward in auth code flow, but the consequences ripple. A wrong choice here turns into secure server OAuth under load, and the invariant you thought auth code flow guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.

The test for Receive the code is the one most teams skip: drive auth code flow to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.

Exchange for tokens

Exchange for tokens is where most auth code flow implementations leak performance. A wrong choice here turns into secure server OAuth under load, and the invariant you thought auth code flow guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.

The test for Exchange for tokens is the one most teams skip: drive auth code flow to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.

test('stores token in session', () => {
  expect(req.session.token).toBeDefined();
});

Pin the behavior with this test. A auth code flow setup that passes this test degrades on purpose instead of by accident, which is the difference between a managed failure and an incident.

Store in session

The hard part of Store in session is not the happy path — it is what happens when auth code flow fails halfway. A wrong choice here turns into secure server OAuth under load, and the invariant you thought auth code flow guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.

The test for Store in session is the one most teams skip: drive auth code flow to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.

Refresh server-side

Refresh server-side should be observable without a debugger. A wrong choice here turns into secure server OAuth under load, and the invariant you thought auth code flow guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.

The test for Refresh server-side is the one most teams skip: drive auth code flow to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.

Test the flow

Test the flow is a trade, not a winner. A wrong choice here turns into secure server OAuth under load, and the invariant you thought auth code flow guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.

The test for Test the flow is the one most teams skip: drive auth code flow to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.

Common pitfalls

The common pitfalls in secure server OAuth all reduce to one mistake: treating auth code flow as a formality instead of a contract. The contract is the thing the rest of the system relies on, and a weak contract propagates weakness everywhere.

  • Skipping the auth code flow boundary so secure server OAuth enters unvalidated.
  • Assuming auth code flow is fast without measuring the tail latency under load.
  • Letting secure server OAuth fail silently instead of failing loudly with a metric.
  • Testing only the happy path so the auth code flow failure surfaces in production.
  • Sharing mutable state across requests so one bad input poisons the next.

Conclusion

Do not conflate the conclusion with the implementation. They look similar from the outside but the failure modes differ: auth code flow fails fast and the caller knows, while an unchecked path fails slow and the caller guesses. Choose the one whose failure mode your system can absorb, and document the choice at the call site.

Self-check: write a test that drives auth code flow to the failing condition and assert the system degrades gracefully. Then secure server OAuth is a property you maintain, not a feature you hope for.

Sources: OAuth 2.0 Auth Code, Passport

FAQ

Why not implicit flow?
It is deprecated. The auth code flow with PKCE is the modern standard.
Store the token?
In the server session, encrypted. Never expose to the browser.

Related Examples