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.
- Create an OAuth app at the provider. Its callback URL is the route of the handler:
https://<your host>/auth/github. - 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:
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:
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:
GITHUB_CLIENT_ID=<the client id of your GitHub OAuth app>
GITHUB_CLIENT_SECRET=<its client secret>
- Make the handler a raw
GETroute whose body isoauthGitHub. A request withoutcodestarts the flow with PKCE and a randomstate; the provider returns to the same route, and youronSuccessgets the profile and the tokens. Returning nothing redirects toauth.redirect.home:
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) } })
},
}),
})
- Link to
/auth/githubfrom the login page. In production setredirectURLon the call or underauth.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 guide.
See also: Auth, @hamur/auth reference.