🗝️

NextAuth v5でGithub認証やってみた

2024/04/12に公開

はじめに

NextAuth v5 の記事が少なかったので、メモ程度ですが書いていこうと思います。

環境

"next": "14.1.4",
"next-auth": "^5.0.0-beta.15",

github OAuthApps 設定

OAuth 認証の設定をします

profile > setting > Developer Settings > OAuth App

Homepage URL

http://localhost:3000

Authorization callback URL

http://localhost:3000/api/auth/callback/github


AuthApp 設定

route を設定する

api/auth/[...next-auth]
このようにフォルダを作成し、route.ts ファイルを作成します。

後ほど設定する auth.ts から handlers を import
GET,POST メソッドを定義します。

api/auth/[...next-auth]/route.ts
import { handlers } from "@/auth/auth";

export const { GET, POST } = handlers;

auth.ts 記述

Github プロバイダーを設定し、それぞれ export します

GITHUB_CLIENT_ID
GITHUB_CLIENT_SECRET
上記の二つはOAuthAppsで設定したappの画面から持ってきます

auth.ts
import NextAuth, { NextAuthConfig } from "next-auth";
import GithubProvider from "next-auth/providers/github";

const config: NextAuthConfig = {
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
    }),
  ],
  basePath: "/api/auth",
};

export const { handlers, auth, signIn, signOut } = NextAuth(config);

サインインしてみる

サインイン、サインアウト用のボタンを定義します

auth_button
import { auth, signIn, signOut } from "@/auth/auth";

export async function SignInButton() {
  const session = await auth();
  if (!session?.user)
    return (
      <>
        <form
          action={async () => {
            "use server";
            await signIn();
          }}
        >
          <button type='submit'>Sign in</button>
        </form>
      </>
    );
}

export async function SignOutButton() {
  return (
    <>
      <form
        action={async () => {
          "use server";
          await signOut();
        }}
      >
        <button type='submit'>Sign out</button>
      </form>
    </>
  );
}

参考文献

https://authjs.dev/

https://authjs.dev/getting-started/authentication/oauth?provider=github

GitHubで編集を提案

Discussion