NextAuthで認証
NextAuthの準備
認証処理をuseContext から NextAuthに置き換えるために必要なファイルなどを準備します。
.env設定
「.env.development」に、NextAuthのURLとシークレットを追加します。
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=vhXFoNfKN2hvFXaRKI=
JWT_SECRET=vhXFoNfKN2hvFXaRKI=
- シークレットはセキュリティ上、openssl などで生成したランダム文字で設定します。
Typeのカスタマイズ
NextAuthの「Session.user」オブジェクトは「id」「name」「email」プロパティのみです。型定義で「accessToken」を設定できるように「types/next-auth.d.ts」を作成します。
accessToken追加
「Session.user」を上書きします。
import NextAuth from "next-auth/next";
declare module "next-auth" {
interface Session {
user : {
id: number;
name: string;
email: string;
accessToken: string;
}
}
}
Middleware修正
Middlewareを、NextAuth用の設定に変更します。
middleware.ts
export { default } from "next-auth/middleware";
// 以前の設定はコメントアウトまたは削除
export const config = {
matcher: ["/", "/user/:path*", "/user/:slug*"]
};
- 以前に設定した Middleware の設定はコメントアウトまたは削除します。
NextAuth設定
API作成
「app/api/auth/[...nextauth]/route.ts」を作成します。
NextAuthOptions設定
NextAuthOptionsに認証に関する設定をします。
| 項目 | 設定 | 値 | |
|---|---|---|---|
| ログインページ | pages | signIn | /auth/login |
| エラーページ | pages | error | /auth/login |
| セッション | session | strategy | JWT |
| プロバイダー | providers | CredentialsProvider | Email、Password |
app/api/auth/[...nextauth]/route.ts
import NextAuth, { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { cookies } from "next/headers";
export const authOptions: NextAuthOptions = {
pages: {
signIn: '/auth/login',
error: '/auth/login',
},
session: { strategy: "jwt" },
providers: [
CredentialsProvider({
name: "Sign in",
credentials: {
email: { label: 'Email', type: 'email', placeholder: 'Email' },
password: { label: 'Password', type: 'password', placeholder: 'Password' }
},
async authorize(credentials) {
},
}),
],
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST }
認証処理
authorize() に認証処理を追加します。認証が成功したら、アクセストークンをCookieに保存し、ユーザ情報を返します。
app/api/auth/[...nextauth]/route.ts
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
...
async authorize(credentials) {
console.log("authorize():", credentials)
if (!credentials?.email || !credentials?.password) return;
const result = await signIn(credentials);
if (result?.access_token) {
await cookies().set('access_token', result.access_token);
const user = await getUser(result?.access_token);
return user;
}
return false;
},
}),
],
}
コールバック
authorize() に各コールバックの処理を追加します。
app/api/auth/[...nextauth]/route.ts
export const authOptions: NextAuthOptions = {
callbacks: {
async signIn({ user, account, profile, email, credentials }) {
return true;
},
async redirect({ url, baseUrl }) {
return baseUrl
},
async jwt({ token, user }) {
return { ...token, ...user }
},
async session({ session, token }) {
session.user = token as Session["user"];
return session;
},
}
}
NextAuthの利用
NextAuthProviderの作成
Providerファイル作成
「app/providers/NextAuthProvider.tsx」を作成します。
SessionProvider
NextAuthProviderで、SessionProviderコンポーネントを読み込んで、子コンポーネント(children)を囲みます。
app/providers/NextAuthProvider.tsx
"use client";
import { SessionProvider } from "next-auth/react";
type Props = {
children?: React.ReactNode;
};
export const NextAuthProvider = ({ children }: Props) => {
return (
<SessionProvider>
{children}
</SessionProvider>
)
};
NextAuthProviderの利用
レイアウトファイルで、NextAuthProviderを親コンポーネントとします。 これで「Navbar」と「children」でSessionが利用できます。
app/layout.tsx
import type { Metadata } from 'next'
import './globals.css'
import Navbar from '@/app/components/Navbar';
// NextAuthProviderインポート
import { NextAuthProvider } from '@/app/providers/NextAuthProvider';
export const metadata: Metadata = {
title: 'Next Tweet',
description: 'This is tweet app sample.',
}
export default async function RootLayout({
children,
}: {
children: React.ReactNode,
}) {
return (
<html lang="ja">
<body>
{/* NextAuthProvider に変更 */}
<NextAuthProvider>
<Navbar />
<main className="flex min-h-screen flex-col p-5">
{children}
</main>
</NextAuthProvider>
</body>
</html>
)
}
useSessionの利用
useContextからuseSessionでユーザ情報を取得するように、各種ページを修正します。
トップページ
app/page.tsx
export default function Home() {
const { data: session } = useSession();
const user: User = session?.user as User;
const [tweets, setTweets] = useState<Tweet[]>([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
(async () => {
if (!user?.accessToken) return;
setIsLoading(true)
const data = await getTweets(user?.accessToken);
setTweets(data);
setIsLoading(false)
})();
}, [user]);
...
}
コース内レッスン
- 1
Lesson 1
はじめるまえに
レッスンを見る - 2
Lesson 2
プロジェクト作成 - Laravel -
レッスンを見る - 3
Lesson 3
API処理 1
レッスンを見る - 4
Lesson 4
Postman
レッスンを見る - 5
Lesson 5
ユーザ認証API
レッスンを見る - 6
Lesson 6
API処理 2
レッスンを見る - 7
Lesson 7
プロジェクト作成 - Next.js -
レッスンを見る - 8
Lesson 8
レイアウト
レッスンを見る - 9
Lesson 9
コンポーネントの基本1
レッスンを見る - 10
Lesson 10
コンポーネントの基本2
レッスンを見る - 11
Lesson 11
コンポーネントの基本3
レッスンを見る - 12
Lesson 12
ルーティング
レッスンを見る - 13
Lesson 13
useState
レッスンを見る - 14
Lesson 14
モデルとサービス
レッスンを見る - 15
Lesson 15
useEffect
レッスンを見る - 16
Lesson 16
useRouter
レッスンを見る - 16
Lesson 16
プロパティ(props)
レッスンを見る - 17
Lesson 17
Cookie
レッスンを見る - 18
Lesson 18
useContext
レッスンを見る - 19
Lesson 19
NextAuth
レッスンを見る - 20
Lesson 20
NextAuthで認証
レッスンを見る