はじめに
SSR(Server Side Rendering)の場合はセッションを使ってユーザー認証管理は一般的です。
Next.jsもいくつかのセッション管理ツールがありますので、少しまとめてみます。
next-authとは
The NextAuth library uses Express and Passport, the most commonly used authentication library for Node.js, to provide support for signing in with email and with services like Facebook, Google and Twitter.
NextAuth adds Cross Site Request Forgery (CSRF) tokens and HTTP Only cookies, supports universal rendering and does not require client side JavaScript.
next-auth: https://github.com/iaincollins/next-auth
インストール
npm install next-auth
クライアント使うサンプル
import React from 'react'
import { NextAuth } from 'next-auth/client'
export default class extends React.Component {
static async getInitialProps({req}) {
return {
session: await NextAuth.init({req})
}
}
render() {
if (this.props.session.user) {
return(
<div>
<p>ログイン中です。</p>
</div>
)
} else {
return(
<div>
<p>未ログインです。</p>
</div>
)
}
}
}
サーバ側
./pages/authフォルダーにページ作成
- index.js NextAuth.signinメソッドを実行し、ログイン成功、失敗を判断
- error.js 認証失敗の処理
重要な3つの設定ファイル
next-auth.config.js: https://github.com/iaincollins/next-auth/blob/master/example/next-auth.config.js
セッションの保存時間、DBなどの設定next-auth.functions.js:https://github.com/iaincollins/next-auth/blob/master/example/next-auth.functions.js
ログインの処理、セッションに保存するデータなどnext-auth.providers.js:https://github.com/iaincollins/next-auth/blob/master/example/next-auth.providers.js
Facebook、Twitter、GoogleなどのproviderのクライアントID,シークレットなどの情報を設定
利用しない場合は設定なしでOKです。
参考:https://github.com/iaincollins/next-auth
サンプル:https://github.com/iaincollins/next-auth/blob/master/example/pages/auth/index.js
passport
passport:http://www.passportjs.org/
cookie
サンプル:https://github.com/zeit/next.js/tree/canary/examples/with-cookie-auth
firebase
サンプル:https://github.com/zeit/next.js/tree/canary/examples/with-firebase-authentication
以上