🙄

JWT Authentication【5Cookie httpOnly】

2022/10/07に公開約2,800字

JWT Authentication【5Cookie httpOnly】

YouTube: https://youtu.be/n6Gze5MclQY

cookie : https://www.npmjs.com/package/cookie

{
    "email": "john@mail.com",
    "password": "john"
}
npm i cookie
npm i --save-dev @types/cookie
  "dependencies": {
    "@prisma/client": "^4.3.1",
    "bcrypt": "^5.0.1",
    "cookie": "^0.5.0",
    "cors": "^2.8.5",
    "express": "^4.18.1",
    "helmet": "^6.0.0",
    "jsonwebtoken": "^8.5.1",
    "morgan": "^1.10.0"
  },
  "devDependencies": {
    "@types/bcrypt": "^5.0.0",
    "@types/cookie": "^0.5.1",
    "@types/cors": "^2.8.12",
    "@types/express": "^4.17.14",
    "@types/jsonwebtoken": "^8.5.9",
    "@types/morgan": "^1.9.3",
    "@types/node": "^18.7.18",
    "prisma": "^4.3.1",
    "ts-node-dev": "^2.0.0",
    "typescript": "^4.8.3"
  }
authControllers.ts
import { Request, Response } from 'express'
import { prisma } from '../utils/prismaClient'
import bcrypt from 'bcrypt'
import jwt from 'jsonwebtoken'
import { jwtSecretKey } from '../utils/jwtSecretKey'
import cookie from 'cookie'

export const register = async (req: Request, res: Response) => {
  const { email, name, password, confirm_password } = req.body

  if (password !== confirm_password ) {
    res.status(400).json({
      'message': "Password do not match confirm password."
    })
    return
  }

  const hashedPassword = await bcrypt.hash(password, 10)

  try {
    const user = await prisma.user.create({
      data: {
        email: email,
        name: name,
        password: hashedPassword
      },
      select: {
        id: true,
        email: true,
        name: true,
      }
    })
    res.status(200).json(user)
  } catch (error) {
    res.status(500).json({"error": error})
  }
}

export const login = async (req: Request, res: Response) => {
  const { email, password } = req.body

  try {
    const user = await prisma.user.findUnique({
      where: {
        email: email
      },
      select: {
        id: true,
        name: true,
        email: true,
        password: true
      }
    })

    if (user === null) {
      return res.status(404).json({error: "user do not exist"})
    }

    const compared = await bcrypt.compare(password, user.password)

    if (!compared) {
      return res.status(400).json({error: "password wrong"})
    }

    const token = jwt.sign({userId: user.id}, jwtSecretKey, {algorithm: 'HS256'})

    if (token) {
      res.setHeader('Set-Cookie', cookie.serialize('jwt', token, {
        httpOnly: true,
        secure: req.app.get('env') !== 'development'
        // secure: true,
        // sameSite: "none"
      }))
    }

    const resUser = {
      id: user.id,
      name: user.name,
      email: user.email
    }

    res.status(200).json(resUser)

  } catch (error: any) {
    res.status(500).json({error: error})
  }
}

Discussion

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