この記事の要点
• OAuth 2.0の認証フロー(認可コードグラント)を理解する
• NextAuth.jsでGoogleログインを簡単に実装する
• セッション管理と保護されたルートでセキュアなアプリを構築する
このチュートリアルで学ぶこと
- OAuthの仕組み
- NextAuth.jsのセットアップ
- Googleプロバイダー設定
- セッション管理
- 保護されたルート
Step 1: セットアップ
npx create-next-app@latest oauth-demo --typescript
cd oauth-demo
npm install next-auth
実践メモ: next-authはGoogle以外にもGitHub、Discord、Twitterなど多数のOAuthプロバイダーに対応しています。
Step 2: Google認証情報の取得
- Google Cloud Console (console.cloud.google.com)
- 新しいプロジェクト作成
- APIとサービス → 認証情報
- OAuth 2.0 クライアントID作成
- 承認済みリダイレクトURI: http://localhost:3000/api/auth/callback/google
Step 3: NextAuth設定
// app/api/auth/[...nextauth]/route.ts
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
const handler = NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}),
],
callbacks: {
async session({ session, token }) {
session.user.id = token.sub;
return session;
},
},
});
export { handler as GET, handler as POST };
注意: NEXTAUTH_SECRETは必ずランダムな文字列を設定してください。openssl rand -base64 32で安全な値を生成できます。
Step 4: 環境変数
# .env.local
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=your-secret-key
Step 5: SessionProvider
// app/providers.tsx
'use client';
import { SessionProvider } from 'next-auth/react';
export function Providers({ children }: { children: React.ReactNode }) {
return <SessionProvider>{children}</SessionProvider>;
}
// app/layout.tsx
import { Providers } from './providers';
export default function RootLayout({ children }) {
return (
<html>
<body>
<Providers>{children}</Providers>
</body>
</html>
);
}
Step 6: ログインボタン
// components/AuthButton.tsx
'use client';
import { signIn, signOut, useSession } from 'next-auth/react';
export function AuthButton() {
const { data: session } = useSession();
if (session) {
return (
<div>
<p>Welcome, {session.user?.name}</p>
<button onClick={() => signOut()}>Sign out</button>
</div>
);
}
return <button onClick={() => signIn('google')}>Sign in with Google</button>;
}
Step 7: 保護されたページ
// app/dashboard/page.tsx
import { getServerSession } from 'next-auth';
import { redirect } from 'next/navigation';
export default async function Dashboard() {
const session = await getServerSession();
if (!session) {
redirect('/api/auth/signin');
}
return <h1>Welcome, {session.user?.name}</h1>;
}
まとめ
NextAuth.jsでOAuth認証を簡単に実装できます。Google以外にもGitHub、Twitterなど多くのプロバイダーに対応しています。