🙌

JWT Authentication【8Auth Middleware】

2022/10/10に公開約1,000字

JWT Authentication【8Auth Middleware】

YouTube: https://youtu.be/iieAw7IDQB8

authMiddleware.ts
import {Request, Response, NextFunction} from 'express'
import jwt from 'jsonwebtoken'
import cookie from 'cookie'
import { jwtSecretKey } from '../utils/jwtSecretKey'

export const isAuthenticated = async (req: Request, res: Response, next: NextFunction) => {
  const cookies = cookie.parse(req.headers.cookie || '')
  const token = cookies.jwt || false

  if (!token) {
    return res.status(401).json({
      message: "Unauthorized - Please login first",
      user: null
    })
  }

  jwt.verify(token, jwtSecretKey, (err, user) => {
    if (err) {
      res.setHeader('Set-Cookie', cookie.serialize('jwt', '', {
        httpOnly: true,
        secure: req.app.get('env') !== 'development',
        maxAge: Number(new Date(0)),
        // secure: true,
        // sameSite: "none"
      }))
      return res.status(400).json({
        message: 'Token is Invalid',
        user: null
      })
    }
    req.user = user
    next()
  })
}

Discussion

ログインするとコメントできます