개발자

next.js 14 nextAuth v4 JWT_SESSION_ERROR 도와주세요..

2023년 12월 28일조회 497

getServerSession 부분에서 JWEDecryprionFailed 에러가 발생하고 있습니다 구글링 결과 authOptions에 secret을 추가하면 된다고 해서 추가해도 계속 발생하네요.. 클라이언트나 서버 컴포넌트에서는 seesion이 가져와 지는데 api 라우트 부분에서만 Session Handling이 안되네요 https://next-auth.js.org/errors#jwt_session_error 콘솔에 출력된 공식 문서를 봐도 해결이 안되네요 도움을 주실분 계신가요..??

1// api 
2import { connectToDatabase } from "@/lib/db";
3import { hashPassword, verifyPassword } from "@/lib/auth";
4import { getServerSession } from "next-auth/next";
5import authOptions from "@/pages/api/auth/[...nextauth]";
6
7export default async function handler(req, res) {
8  if (req.method !== "PATCH") {
9    return;
10  }
11
12  // TODO api route 에서 session 가져올 수 있게 수정
13  // const session = await getSession({ req: req });
14  const session = await getServerSession(req, res, authOptions);
15
16  console.log("session", session);
17
18...
19
20//[...nextauth].js
21
22
23import NextAuth from "next-auth/next";
24import CredentialsProvider from "next-auth/providers/credentials";
25
26import { connectToDatabase } from "@/lib/db";
27import { verifyPassword } from "@/lib/auth";
28
29const authOptions = {
30  session: {
31    strategy: "jwt",
32  },
33  secret: process.env.nextauth_secret,
34  providers: [
35    CredentialsProvider({
36      async authorize(credentials) {
37        const client = await connectToDatabase();
38        const usersCollection = client.db().collection("users");
39        const user = await usersCollection.findOne({
40          email: credentials.email,
41        });
42
43        console.log("user", user);
44
45        if (!user) {
46          client.close();
47          throw new Error("No user found!");
48        }
49
50        const isValid = await verifyPassword(
51          credentials.password,
52          user.password
53        );
54
55        if (!isValid) {
56          client.close();
57          throw new Error("Could not log you in!");
58        }
59
60        client.close();
61        return { email: user.email };
62      },
63    }),
64  ],
65};
66
67export default (req, res) => NextAuth(req, res, authOptions);
68
69//next.config.js
70const { PHASE_DEVELOPMENT_SERVER } = require("next/constants");
71
72const nextConfig = (phase) => {
73  if (phase === PHASE_DEVELOPMENT_SERVER) {
74    return {
75      env: {
76        nextauth_secret: "ewxfRY4GUAF4OqboINdV504mhp/8ik6n/qea1X7WMnM",
77      },
78    };
79  }
80
81  return {
82    env: {
83      nextauth_secret: "ewxfRY4GUAF4OqboINdV504mhp/8ik6n/qea1X7WMnM",
84    },
85  };
86};
87
88module.exports = nextConfig;
89
90//error
91[next-auth][error][JWT_SESSION_ERROR] 
92https://next-auth.js.org/errors#jwt_session_error decryption operation failed {
93  message: 'decryption operation failed',
94  stack: 'JWEDecryptionFailed: decryption operation failed\n' +
95    '    at gcmDecrypt (/Users/nonamedbread/code/NextJs_Practice/node_modules/jose/dist/node/cjs/runtime/decrypt.js:67:15)\n' +
96    '    at decrypt (/Users/nonamedbread/code/NextJs_Practice/node_modules/jose/dist/node/cjs/runtime/decrypt.js:92:20)\n' +
97    '    at flattenedDecrypt (/Users/nonamedbread/code/NextJs_Practice/node_modules/jose/dist/node/cjs/jwe/flattened/decrypt.js:143:52)\n' +
98    '    at async compactDecrypt (/Users/nonamedbread/code/NextJs_Practice/node_modules/jose/dist/node/cjs/jwe/compact/decrypt.js:18:23)\n' +
99    '    at async jwtDecrypt (/Users/nonamedbread/code/NextJs_Practice/node_modules/jose/dist/node/cjs/jwt/decrypt.js:8:23)\n' +
100    '    at async Object.decode (/Users/nonamedbread/code/NextJs_Practice/node_modules/next-auth/jwt/index.js:66:7)\n' +
101    '    at async Object.session (/Users/nonamedbread/code/NextJs_Practice/node_modules/next-auth/core/routes/session.js:43:28)\n' +
102    '    at async AuthHandler (/Users/nonamedbread/code/NextJs_Practice/node_modules/next-auth/core/index.js:165:27)\n' +
103    '    at async getServerSession (/Users/nonamedbread/code/NextJs_Practice/node_modules/next-auth/next/index.js:159:19)\n' +
104    '    at async handler (webpack-internal:///(api)/./pages/api/user/change-password.js:20:21)',
105  name: 'JWEDecryptionFailed'
106}
107session null
이 질문이 도움이 되었나요?
'추천해요' 버튼을 누르면 좋은 질문이 더 많은 사람에게 노출될 수 있어요. '보충이 필요해요' 버튼을 누르면 질문자에게 질문 내용 보충을 요청하는 알림이 가요.

답변 1

김태우님의 프로필 사진

page 디렉터리에 api라우트인 거죠?

이규환님의 프로필 사진

이규환

작성자

Cogent 풀스택 개발자, BI2023년 12월 29일

네 맞습니다 구글링을 좀 더 해본결과 쿠키가 전달이 안돼서 그렇다는데 https://github.com/nextauthjs/next-auth/issues/7423 api 요청을 components/profile/user-profile.js 에서 요청하고 있는데 클라이언트 컴포넌트에서 쿠키를 전달할 방법을 찾지 못해서 해결 못하고 있습니다..

김태우님의 프로필 사진

김태우

zzambbong developer2023년 12월 29일

그럼 응답을 보내줄 때 쿠키를 설정해주면 될 거 같은데요! 혹시 서버컴포넌트에서 요청을 보내고 서버컴포넌트로 응답을 보내고 계신가요? 그러면 헤더에 쿠키를 넣어서 응답을 보내줘도 저장이 안됩니다. 요청보내는 부분을 클라이언트 컴포넌트로 따로 빼셔야 할 거에요!

김태우님의 프로필 사진

김태우

zzambbong developer2023년 12월 29일

응답으로 쿠키가 설정됐으면 따로 전달할 필요가 없습니다. 그리고 위 링크는 app디렉터리에 api라우트 같은데요..!?

지금 가입하면 모든 질문의 답변을 볼 수 있어요!

현직자들의 명쾌한 답변을 얻을 수 있어요.

또는

이미 회원이신가요?

AI 답변
커리어리 AI 봇 프로필 이미지

커리어리 AI 봇

GPT가 달아주는 답변입니다.

2023년 12월 28일

제공하신 코드를 보면, `secret: process.env.nextauth_secret`가 정의되어 있는데 이 값이 next.config.js 파일에서 환경 변수로 설정되어 있습니다. 이 에러는 일반적으로 JWT 암호화 및 복호화 과정에서 나오는 오류입니다. 사용된 secret 값이 일관되지 않으면 문제가 발생할 수 있습니다. `nextauth_secret`의 값을 확인해보세요. 이 환경변수는 `.env.local`, `.env.development`, `.env.production` 등에서 관리될 수 있습니다. 그리고 로컬 개발환경과 배포환경 모두에 같은 secret값을 가지도록 하세요. 위 조치들을 취해도 문제가 해결되지 않는다면, 다음을 따라해보세요: 1. 종료: `npm run dev` or `yarn dev` 2. 프로젝트 루트 폴더에서 `.next/` 폴더를 삭제하세요. 3. 삭제 후, 서버를 재시작합니다 `npm run dev` or `yarn dev` 이렇게 하면 Next.js의 임시 파일들이 클리어 되면서 문제가 해결될 수 있습니다. 아울러, 사용할 수 있는 경우 최신 버전의 NextAuth와 Next.js를 사용하는 것을 권장합니다. 혹시 계속 문제가 발생한다면, 질문을 다른 상세한 정보와 함께 다시 올려주시기 바랍니다.

목록으로

지금 가입하면 모든 질문의 답변을 볼 수 있어요!