Next.jsでの認証と認可:セキュアなアプリのために

目次

  1. はじめに
  2. 認証と認可の概要
  3. Passport.js とセットアップ
  4. 認証戦略の作成
  5. 認証ルートの作成
  6. クライアントサイドの処理
  7. 認可の実装
  8. セッション管理
  9. さいごに

1. はじめに

この記事では、Next.jsを利用したアプリケーションで認証と認可を実現する方法について説明します。セキュアなアプリケーションを構築するための手法や機能を詳しく解説しましょう。

2. 認証と認可の概要

  • 認証:ユーザーがシステムにアクセスする権限を持っていることを確認
  • 認可:ユーザーに割り当てられた権限に基づいて、システム内で許可されたアクションを制限

3. Passport.js とセットアップ

認証戦略に Passport.js を使用します。必要なモジュールをインストールします。

npm install passport passport-local express-session bcrypt

4. 認証戦略の作成

localStrategy.js:

import passportLocal from 'passport-local'
import bcrypt from 'bcrypt'

const LocalStrategy = passportLocal.Strategy
const users = [] // 仮のユーザーリスト

export default new LocalStrategy(
  async (username, password, done) => {
    const user = users.find((user) => user.username === username)

    if (!user) {
      return done(null, false, { message: 'User not found' })
    }

    const validPassword = await bcrypt.compare(password, user.password)
    if (!validPassword) {
      return done(null, false, { message: 'Incorrect password' })
    }

    return done(null, user)
  }
)

5. 認証ルートの作成

/pages/api/auth.js:

import nextConnect from 'next-connect'
import passport from 'passport'
import localStrategy from '../../localStrategy'

passport.use(localStrategy)

const handler = nextConnect()

handler.use(passport.initialize())

handler.post(passport.authenticate('local'), (req, res) => {
  res.status(200).json({ user: req.user })
})

export default handler

6. クライアントサイドの処理

LoginPage.js:

import { useState } from 'react'
import axios from 'axios'

const LoginPage = () => {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')

  const submitHandler = async (e) => {
    e.preventDefault()

    try {
      const result = await axios.post('/api/auth', { username, password })
      console.log(result.data)
    } catch (error) {
      console.error(error)
    }
  }

  return (
    <form onSubmit={submitHandler}>
      <input type='text' onChange={(e) => setUsername(e.target.value)} />
      <input type='password' onChange={(e) => setPassword(e.target.value)} />
      <button type='submit'>ログイン</button>
    </form>
  )
}

export default LoginPage

7. 認可の実装

アクセス制限を行う関数を定義します。

authMiddleware.js:

export const authMiddleware = (req, res, next) => {
  if (!req.user || !req.isAuthenticated()) {
    return res.status(401).json({ message: 'Unauthorized' })
  }
  next()
}

8. セッション管理

/pages/api/auth.jsにセッション管理を追加します。

import session from 'express-session'

const sessionOptions = {
  secret: 'your-session-secret',
  resave: false,
  saveUninitialized: false,
  secure: process.env.NODE_ENV === 'production',
}

handler.use(session(sessionOptions))
handler.use(passport.session())

9. さいごに

この記事では、Next.jsで認証と認可の方法を学び、セキュアなアプリケーションを作成する際の手法を解説しました。適切な認証・認可機能が整ったアプリケーションで、ユーザーの安全な操作環境を提供しましょう。