3. Logging in with GitHub


Users of this app are going to be engineering teams, and for now they’ll have to have a GitHub account, so “Sign in with GitHub” is the obvious first way in.

This post covers building that login: a Go API that does the secret-bearing part and issues a session, and a React app that drives the rest. It also introduces the shape of the API itself, since until today it was a hello-world net/http server.

The constraints

  • The API is pure REST. No login pages, no redirects, no OAuth state handling. Just JSON endpoints, described by an OpenAPI spec.
  • The client secret only ever lives in the API. The frontend gets the public client id from the API, not from a build-time env var.
  • The API issues the session. After GitHub confirms who you are, the API signs its own short-lived JWT. GitHub’s token is used once and thrown away.
  • No hardcoded domains in the frontend. This isn’t just about my own domain changing later (last post has the hostnames) — one of the non-functional requirements is that other people can self-host this, on whatever domain they own, without patching the app to point it somewhere else.

The flow

The interesting decision is who does the redirecting. GitHub sends the user back to the app, not the API, and the app hands the code to the API:

sequenceDiagram
    participant B as Browser (app)
    participant A as API
    participant G as GitHub

    B->>A: GET /auth/github/config
    A-->>B: clientId, authorizeUrl, scopes
    B->>B: generate state, keep in sessionStorage
    B->>G: redirect to authorize (redirect_uri = app/auth/callback)
    G-->>B: redirect to app/auth/callback?code&state
    B->>B: check state matches
    B->>A: POST /auth/github/login {code, redirectUri}
    A->>G: exchange code (client id + secret)
    G-->>A: access token
    A->>G: GET /user (and /user/emails)
    G-->>A: profile
    A-->>B: 200 {user, expiresAt} + Set-Cookie: session JWT
    B->>A: GET /auth/me (cookie)
    A-->>B: user

Keeping the redirects in the frontend means the API never has to know about pages or browser navigation, and it’s easy to test: it’s a handful of JSON calls. The code exchange has to be server-side anyway, because GitHub’s token endpoint needs the client secret and doesn’t allow CORS requests from a browser.

The API

I’m not fully sold on the structure yet and expect to revisit it, but it’s a reasonable place to start: cmd/server/main.go is now a few lines; everything else lives under internal/:

cmd/server/main.go        # os.Exit(cli.Execute())
internal/cli/             # cobra: root command + `serve`
internal/boot/            # load config, wire dependencies
internal/config/          # the config struct, loading, validation
internal/auth/            # GitHub client, JWT signer
internal/api/             # huma operations, CORS, session middleware

It’s a cobra CLI, so the binary is devflo-server serve and there’s room for other subcommands (migrations, workers) later. The HTTP layer uses Huma on top of the standard library mux, which gives me the OpenAPI spec and /docs for free, generated from the Go types rather than the other way around.

Config

The app boot loads a devflo.server.yaml and binds it to a struct with viper:

server:
  addr: ":8080"
  allowedOrigins:
    - https://app.devflo.test

auth:
  github:
    clientId: ""
    clientSecret: ""
    scopes: [read:user, user:email]
    allowedRedirectUris:
      - https://app.devflo.test/auth/callback
  jwt:
    secret: ""        # at least 32 bytes
    issuer: devflo-api
    audience: devflo-app
    ttl: 1h
  cookie:
    name: devflo_session
    secure: true
    sameSite: lax

The real file holds secrets so it’s gitignored, and a devflo.server.example.yaml is committed instead. Any value can also come from the environment (DEVFLO_AUTH_GITHUB_CLIENTSECRET, and so on), which makes it a bit easier to deploy — you could still mount the whole thing as a file instead, secrets and all, if that suits your setup better.

Two viper details worth knowing. Environment overrides only apply to keys viper already knows about, so every key gets a default, even if that default is an empty string. And validation runs at boot and reports every problem at once, rather than making you fix them one restart at a time:

Error: load config: invalid config: auth.github.clientId is required
auth.github.clientSecret is required
auth.github.allowedRedirectUris must contain at least one URI
auth.jwt.secret must be at least 32 bytes

Endpoints

Endpoint What it does
GET /auth/github/config Returns {clientId, authorizeUrl, scopes}. Public values only.
POST /auth/github/login Takes {code, redirectUri}, exchanges the code, sets the session cookie.
GET /auth/me Returns the logged-in user, or 401.
POST /auth/logout Clears the cookie.
GET /healthz Health check.

The login endpoint only accepts a redirectUri that’s on an allowlist in the config, and maps failures to the right status: 400 for a redirect URI it doesn’t recognise, 401 if GitHub rejects the code, 502 if GitHub is unreachable.

That 401 versus 502 split is worth a note. When you hand GitHub a bad or expired code, it doesn’t respond with an HTTP error: it returns 200 OK with {"error": "bad_verification_code"} in the body. Go’s oauth2 package surfaces that as a RetrieveError, so I treat a RetrieveError with a non-5xx response as “your code was bad” and everything else (network errors, 5xx) as “GitHub is having a moment”.

The session

After the exchange the API fetches the user’s profile, and their primary verified email if the profile’s email is private, then signs an HS256 JWT with the GitHub user id as the subject and the login, name, avatar and email as claims. Verification is deliberately strict: it only accepts HS256 (so no alg: none tricks, and no swapping to another HMAC variant), and it requires the right issuer and audience and a valid expiry.

The JWT is never returned in the response body. It’s set as a cookie:

Set-Cookie: devflo_session=…; Path=/; Max-Age=3600; HttpOnly; Secure; SameSite=Lax

HttpOnly means JavaScript in the page can’t read it, so an XSS bug can’t walk off with the token. That works well here because the app (app.devflo.test) and API (api.devflo.test) are different origins but the same site: the browser will send a SameSite=Lax cookie on fetch calls between them, as long as the request opts in with credentials: 'include' and the API’s CORS config allows credentials for the app’s origin. I left the cookie host-only (no Domain attribute) since the app never needs to read it.

There are no refresh tokens. The JWT lasts an hour and then you log in again, which keeps the API stateless for now (it doesn’t have a database yet).

The frontend

The app was still the standard Vite starter page, so this meant adding a login page, a callback page, and a protected route around it, then wiring all three up to the API.

Finding the API

The app works out where the API is from where it is running, by swapping the leading app for api:

export function getApiBaseUrl(
  location: Pick<Location, 'protocol' | 'hostname'> = window.location,
): string {
  const { protocol, hostname } = location

  if (!hostname.startsWith('app.')) {
    throw new Error(
      `Can't work out the API URL from "${hostname}": open the app on a hostname that starts with "app." (for example app.devflo.test).`,
    )
  }

  return `${protocol}//api.${hostname.slice('app.'.length)}`
}

No env var and no domain in the code, so moving from devflo.test to a real domain later is a config change on the API side only. It throws rather than guessing if you open the app on localhost, since a wrong guess would just be a confusing network error.

The callback

When GitHub redirects back to /auth/callback, the page checks the state it stored before leaving, then sends the code to the API exactly once:

// Authorization codes are single use, so the code must only be sent once,
// even though StrictMode runs this effect twice in development.
const started = useRef(false)

useEffect(() => {
  if (started.current) return
  started.current = true
  // ...check state, then:
  const { user } = await loginWithGithubCode(code, getRedirectUri())
  completeLogin(user)
}, [searchParams, completeLogin])

That useRef guard matters. In development React’s StrictMode runs effects twice, and a second attempt to use the same code would come back as a 401 from GitHub and bounce you to the login page with an error, even though the first attempt had worked.

Knowing who’s logged in

Since the session is an HttpOnly cookie the app can’t inspect, it just asks the API: on load it calls GET /auth/me, and the auth context has three states, loading, authenticated and unauthenticated. The protected route shows a loading state until that resolves rather than flashing the login page.

There’s one subtle race in there. The callback page finishes logging in while that initial /auth/me check might still be in flight, and if the (401) check resolved after the login, it would knock you back to logged out. So the initial check only settles the state if it’s still loading.

Testing it

I wanted the whole thing covered without ever talking to real GitHub, so the GitHub endpoints (authorize, token, API) are configurable, and the tests point them at an httptest server. That let me test the real client code against a fake, including the awkward cases:

  • a bad code (GitHub’s 200 with an error body) becomes a 401, and a 5xx becomes a 502
  • a private profile email falls back to the primary verified email, and a failure to fetch emails doesn’t fail the login
  • a redirectUri that’s close to but not exactly on the allowlist is rejected (wrong scheme, extra path, a lookalike host)
  • /auth/github/config never contains the client secret, and the login response body never contains the JWT
  • tokens signed with the wrong secret, the wrong algorithm (HS384 and none), the wrong issuer or audience, or already expired are all rejected
  • CORS allows the configured origin with credentials and nobody else

That’s about 40 tests, run with the race detector. Booting with a missing or half-filled config file fails with a readable error, which I checked by hand. The UI has no test framework yet, so there it’s lint plus a type-checked production build.

Setting up GitHub

You need to register an OAuth App (Settings → Developer settings → OAuth Apps):

  • Homepage URL: https://app.devflo.test
  • Authorization callback URL: https://app.devflo.test/auth/callback

The callback points at the app, because that’s where GitHub sends the browser, and it must exactly match an entry in allowedRedirectUris. Then copy the client id, generate a client secret (GitHub only shows it once), and put both in devflo.server.yaml alongside a JWT secret from openssl rand -base64 48.

If you find yourself on a form with an “Expire user authorization tokens” checkbox, you’re creating a GitHub App rather than an OAuth App. It works with this flow too, but the setting doesn’t matter here: the API uses GitHub’s token once, right after the exchange, and never stores it. (GitHub Apps ignore the requested scope, so you’d grant read access to email addresses under the app’s account permissions instead.)

What’s next

I’ve left a few things out on purpose:

  • PKCE. The code passes through the browser, so PKCE would be a sensible extra layer: the app generates a verifier and the API sends it along in the exchange.
  • CSRF tokens. SameSite=Lax plus JSON-only POSTs behind CORS is enough while there are only two mutating endpoints, but I’ll want a proper answer before there are more.
  • Refresh tokens. For now, expiry just means logging in again.

The refresh token piece is the next thing I’ll pick up, since a session that dies after an hour with no way to renew it isn’t going to hold up for long once anyone’s actually using this. That needs somewhere to store them, which means the database is next too.