//tips
//smart contract
next-authライブラリを導入していく。
npm install --save next-auth
pages/apiフォルダ下にauthフォルダを作成して[…nextauth].jsファイルを作成。
[…nextauth].jsとすることでURLのメインパス以降を配列として受け取ることが可能になる。
Githubの認証機能を利用できるサンプル内容で実験してみる。
import NextAuth from 'next-auth';
import GithubProvider from 'next-auth/providers/github';
export default NextAuth({
// Configure one or more authentication providers
providers: [
GithubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
// ...add more providers here
],
});
/api/auth/以降のリクエストは自動的にNextAuth.js.で扱われるようになる。
All requests to /api/auth/* (signIn, callback, signOut, etc.) will automatically be handled by NextAuth.js.
.env.local.exampleの中身を設定していく。
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET= # Linux: `openssl rand -hex 32` or go to https://generate-secret.now.sh/32
GITHUB_ID=
GITHUB_SECRET=
基本的な認証の流れを確認。
OAuth flow generally has 6 parts:
ユーザーからのアクセス認証リクエストが認証サーバーへ
The application requests authorization to access service resources from the user
ユーザーが認証サーバからの確認を承認すると、アプリに認証情報が提供される
If the user authorized the request, the application receives an authorization grant
アプリのアクセスに対して、認証サーバから認証情報の確認
The application requests an access token from the authorization server (API) by presenting authentication of its own identity, and the authorization grant
認証されるとアプリに対して、サーバが、認証トークンを発行
If the application identity is authenticated and the authorization grant is valid, the authorization server (API) issues an access token to the application. Authorization is complete.
アプリから情報の要求
The application requests the resource from the resource server (API) and presents the access token for authentication
トークンが有効であれば情報を獲得
If the access token is valid, the resource server (API) serves the resource to the application
Googleとgithubの設定を試してみたが、エラー。
code: 'MISSING_NEXTAUTH_API_ROUTE_ERROR'
こちらが一番わかりやすかった。
https://github.com/nextauthjs/next-auth
gituhubに行き、oauthappを作成。
Register a new OAuth applicationにて、http://localhost:3000/api/auth/callback/githubをcallbackURLに設定。
Apitest.jsファイルを新たにpagesフォルダに作成し、Add React Hookのボタンによる認証設定をペースト。
import { useSession, signIn, signOut } from "next-auth/react"
export default function Component() {
const { data: session } = useSession()
if (session) {
return (
<>
Signed in as {session.user.email} <br />
<button onClick={() => signOut()}>Sign out</button>
</>
)
}
return (
<>
Not signed in <br />
<button onClick={() => signIn()}>Sign in</button>
</>
)
}
実行すると、Error: [next-auth]: `useSession` must be wrapped in a <SessionProvider />とのエラーが発生。
Make sure that <SessionProvider> is added to pages/_app.js.との記載があり、下記を追加。
import { SessionProvider } from "next-auth/react"
export default function App({
Component,
pageProps: { session, ...pageProps },
}) {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
)
}
ページはなんとか表示できるようになったがボタンクリックをしてもきちんと認証providerを読み込まない。
一旦新規のnextプロジェクトを作り挙動をみる。きちんと成功した。index.jsに書き込む必要があったよう。ルートの問題。
認証ボタンの作成と認証はできた。分岐条件がまずいようなので調整。