Theory

How the token rides every request

In lesson 8a we stored the session token, but we haven't sent it anywhere yet. Now — step 4 of the contract: attach the token to every protected request.

The server checks a protected endpoint (say GET /orders) against an HTTP header:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

The "bad" way is to add this header by hand in every repository. Then every piece of code has to think about auth, and you'll forget it somewhere.

The "good" way is one OkHttp interceptor. An interceptor is a filter that every outgoing request passes through. We attach the token there once, and the rest of the app never has to know:

Repository ──▶ Retrofit ──▶ OkHttp ──[AuthInterceptor adds the token]──▶ server

Two things the interceptor must handle:

  • Public paths. /login and /register must NOT carry a token — there isn't one yet at login time. The interceptor skips them.
  • 401 (Unauthorized). If the token is expired or bad, the server returns 401. Then the user should go back to login.

In this lesson: AuthInterceptor attaches the token, coreModule gains a real OkHttpClient, and finally we get ordersPOST /orders (place) and GET /orders (history). From the token the server knows whose orders these are, so each user sees only their own.