# OAuth login

Goal: a "Sign in with GitHub" link that ends with the user in the same session as the password login of [Auth with sessions](/recipes/auth-with-sessions).

1. Create an OAuth app at the provider. Its callback URL is the route of the handler: `https://<your host>/auth/github`.
2. Give the id and secret to the server through the environment, so nothing secret sits in the repository. Declare both variables in `app/env.ts`:

````ts [recipes/oauth-env.ts]
import { defineEnv } from "hamur"

export default defineEnv({
  GITHUB_CLIENT_ID: {},
  GITHUB_CLIENT_SECRET: {},
})
````

and read them in `auth.oauth.github` with `env("NAME")`, which the server resolves when it starts:

````ts [recipes/oauth-config.ts]
import { defineConfig, env } from "hamur"
import auth from "@hamur/auth"

export default defineConfig({
  framework: "react",
  modules: [auth],
  auth: {
    oauth: { github: { clientId: env("GITHUB_CLIENT_ID"), clientSecret: env("GITHUB_CLIENT_SECRET") } },
  },
})
````

Set them where the server runs, or in `.env` for `hamur dev`:

````env [recipes/oauth.env]
GITHUB_CLIENT_ID=<the client id of your GitHub OAuth app>
GITHUB_CLIENT_SECRET=<its client secret>
````

3. Make the handler a raw `GET` route whose body is `oauthGitHub`. A request without `code` starts the flow with PKCE and a random `state`; the provider returns to the same route, and your `onSuccess` gets the profile and the tokens. Returning nothing redirects to `auth.redirect.home`:

````ts [recipes/oauth-github.ts]
import { oauthGitHub, setUserSession } from "@hamur/auth/server"
import { defineHandler } from "hamur/server"

export const github = defineHandler({
  route: "/auth/github",
  method: "GET",
  raw: true,
  handler: oauthGitHub({
    async onSuccess(event, { user }) {
      await setUserSession(event, { user: { id: String(user.id), name: String(user.login) } })
    },
  }),
})
````

4. Link to `/auth/github` from the login page. In production set `redirectURL` on the call or under `auth.oauth.github`, because the default is built from the request.

Every other provider is a function of the same shape, `oauthGoogle`, `oauthDiscord`, `oauthMicrosoft` and the rest; OpenID Connect and AT Protocol have their own. Putting the id of a provider's user next to your own users, and sending the visitor back to the page they came from, are in the [Auth](/auth#oauth) guide.

See also: [Auth](/auth), [`@hamur/auth` reference](/api-reference/auth).
