OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

NextAuth GetServerSession JWT Session Error

  • Thread starter Thread starter Sam Madden
  • Start date Start date
S

Sam Madden

Guest
I'm trying to secure one of my API routes in my NextJS application, however I keep receiving a JWT Session Error. This has been quite annoying because I am building out a pretty simple use case and I didn't think I was using JWT at all. From what I could find of the next-auth documentation, securing an api endpoint seemed quite easy. Below are snippets of my code.

Using "next-auth": "^4.24.5", "react": "18.2.0",

pages/api/reviews​


Here, I tried to secure the PUT endpoint

Code:
import pool from "../../../backend-utils";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";

export default async function handler(req, res){

    const method = req.method;
      
    if (method == "GET"){
    try{
        const client = await pool.connect()
        const data = await client.query('SELECT * FROM reviews;');
        res.status(200).json({ body: data });
    catch (error) {
        res.status(500).json({message: "There was an error and we could not complete your get all reviews request. Error: "+ error});
     }
    else if (method == "PUT"){
        try{

            const session = await getServerSession(req, res, authOptions);
            if (!session) {
                return res.status(500).json({ message: 'The request was unauthorized' });
            }

            const {rest_name, o_rating, price, taste, experience, description, city, state_code} = JSON.parse(req.body);
            const response = await pool.query(`INSERT INTO reviews(rest_name, o_rating, price, taste, experience, description, city, state_code, user_id_submitted, soph_submitted) VALUES ('${rest_name}', ${o_rating}, ${price}, ${taste}, ${experience}, '$<p>I'm trying to secure one of my API routes in my NextJS application, however I keep receiving a JWT Session Error. This has been quite annoying because I am building out a pretty simple use case and I didn't think I was using JWT at all. From what I could find of the <a href="https://next-auth.js.org/tutorials/securing-pages-and-api-routes#securing-api-routes" rel="nofollow noreferrer">next-auth documentation</a>, securing an api endpoint seemed quite easy. Below are snippets of my code.</p>
<p>Using "next-auth": "^4.24.5", "react": "18.2.0",</p>
<h1>pages/api/reviews</h1>
<h1></h1>
<p>Here, I tried to secure the PUT endpoint</p>
<pre><code>import pool from "../../../backend-utils";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";

export default async function handler(req, res){

    const method = req.method;
      
    if (method == "GET"){
    try{
        const client = await pool.connect()
        const data = await client.query('SELECT * FROM reviews;');
        res.status(200).json({ body: data });
    catch (error) {
        res.status(500).json({message: "There was an error and we could not complete your get all reviews request. Error: "+ error});
     }
    else if (method == "PUT"){
        try{

            const session = await getServerSession(req, res, authOptions);
            if (!session) {
                return res.status(500).json({ message: 'The request was unauthorized' });
            }

            const {rest_name, o_rating, price, taste, experience, description, city, state_code} = JSON.parse(req.body);
            const response = await pool.query(`INSERT INTO reviews(rest_name, o_rating, price, taste, experience, description, city, state_code, user_id_submitted, soph_submitted) VALUES ('${rest_name}', ${o_rating}, ${price}, ${taste}, ${experience}, '${description}', '${city}', '${state_code}', '1', FALSE);`);
            res.status(200).json({message: response, body: req.body})
        } catch (error){
            res.status(500).json({ message: error })
        }
    }

}
</code></pre>
<h1>pages/api/auth/[...nextauth].js</h1>
<h1></h1>
<pre><code>import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google";

export const authOptions = {
  // Configure one or more authentication providers
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      authorization: {
        params: {
          prompt: "consent",
          access_type: "offline",
          response_type: "code"
        }
      }
    })
  ]
}
export default NextAuth(authOptions)
</code></pre>
<h1>Error</h1>
<pre><code>https://next-auth.js.org/errors#jwt_session_error decryption operation failed {
  message: 'decryption operation failed',
  stack: 'JWEDecryptionFailed: decryption operation failed\n' +
    '    at gcmDecrypt (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/jose/dist/node/cjs/runtime/decrypt.js:67:15)\n' +
    '    at decrypt (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/jose/dist/node/cjs/runtime/decrypt.js:92:20)\n' +
    '    at flattenedDecrypt (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/jose/dist/node/cjs/jwe/flattened/decrypt.js:143:52)\n' +
    '    at async compactDecrypt (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/jose/dist/node/cjs/jwe/compact/decrypt.js:18:23)\n' +
    '    at async jwtDecrypt (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/jose/dist/node/cjs/jwt/decrypt.js:8:23)\n' +
    '    at async Object.decode (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/next-auth/jwt/index.js:66:7)\n' +
    '    at async Object.session (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/next-auth/core/routes/session.js:43:28)\n' +
    '    at async AuthHandler (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/next-auth/core/index.js:165:27)\n' +
    '    at async getServerSession (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/next-auth/next/index.js:159:19)\n' +
    '    at async unstable_getServerSession (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/next-auth/next/index.js:195:10)\n' +
    '    at async handler (webpack-internal:///(api)/./pages/api/reviews/index.js:35:34)',
  name: 'JWEDecryptionFailed'
}
</code></pre>
<p>Let me know if you need any more information.</p>
<p>I tried to secure an endpoint using <code>getServerSession(req, res, authOptions)</code>, but I kept receiving a JWT error.</p>', '${city}', '${state_code}', '1', FALSE);`);
            res.status(200).json({message: response, body: req.body})
        } catch (error){
            res.status(500).json({ message: error })
        }
    }

}

pages/api/auth/[...nextauth].js​


Code:
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google";

export const authOptions = {
  // Configure one or more authentication providers
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      authorization: {
        params: {
          prompt: "consent",
          access_type: "offline",
          response_type: "code"
        }
      }
    })
  ]
}
export default NextAuth(authOptions)

Error​


Code:
https://next-auth.js.org/errors#jwt_session_error decryption operation failed {
  message: 'decryption operation failed',
  stack: 'JWEDecryptionFailed: decryption operation failed\n' +
    '    at gcmDecrypt (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/jose/dist/node/cjs/runtime/decrypt.js:67:15)\n' +
    '    at decrypt (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/jose/dist/node/cjs/runtime/decrypt.js:92:20)\n' +
    '    at flattenedDecrypt (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/jose/dist/node/cjs/jwe/flattened/decrypt.js:143:52)\n' +
    '    at async compactDecrypt (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/jose/dist/node/cjs/jwe/compact/decrypt.js:18:23)\n' +
    '    at async jwtDecrypt (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/jose/dist/node/cjs/jwt/decrypt.js:8:23)\n' +
    '    at async Object.decode (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/next-auth/jwt/index.js:66:7)\n' +
    '    at async Object.session (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/next-auth/core/routes/session.js:43:28)\n' +
    '    at async AuthHandler (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/next-auth/core/index.js:165:27)\n' +
    '    at async getServerSession (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/next-auth/next/index.js:159:19)\n' +
    '    at async unstable_getServerSession (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/next-auth/next/index.js:195:10)\n' +
    '    at async handler (webpack-internal:///(api)/./pages/api/reviews/index.js:35:34)',
  name: 'JWEDecryptionFailed'
}

Let me know if you need any more information.

I tried to secure an endpoint using getServerSession(req, res, authOptions), but I kept receiving a JWT error.

<p>I'm trying to secure one of my API routes in my NextJS application, however I keep receiving a JWT Session Error. This has been quite annoying because I am building out a pretty simple use case and I didn't think I was using JWT at all. From what I could find of the <a href="https://next-auth.js.org/tutorials/securing-pages-and-api-routes#securing-api-routes" rel="nofollow noreferrer">next-auth documentation</a>, securing an api endpoint seemed quite easy. Below are snippets of my code.</p>
<p>Using "next-auth": "^4.24.5", "react": "18.2.0",</p>
<h1>pages/api/reviews</h1>
<h1></h1>
<p>Here, I tried to secure the PUT endpoint</p>
<pre><code>import pool from "../../../backend-utils";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";

export default async function handler(req, res){

const method = req.method;

if (method == "GET"){
try{
const client = await pool.connect()
const data = await client.query('SELECT * FROM reviews;');
res.status(200).json({ body: data });
catch (error) {
res.status(500).json({message: "There was an error and we could not complete your get all reviews request. Error: "+ error});
}
else if (method == "PUT"){
try{

const session = await getServerSession(req, res, authOptions);
if (!session) {
return res.status(500).json({ message: 'The request was unauthorized' });
}

const {rest_name, o_rating, price, taste, experience, description, city, state_code} = JSON.parse(req.body);
const response = await pool.query(`INSERT INTO reviews(rest_name, o_rating, price, taste, experience, description, city, state_code, user_id_submitted, soph_submitted) VALUES ('${rest_name}', ${o_rating}, ${price}, ${taste}, ${experience}, '${description}', '${city}', '${state_code}', '1', FALSE);`);
res.status(200).json({message: response, body: req.body})
} catch (error){
res.status(500).json({ message: error })
}
}

}
</code></pre>
<h1>pages/api/auth/[...nextauth].js</h1>
<h1></h1>
<pre><code>import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google";

export const authOptions = {
// Configure one or more authentication providers
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
authorization: {
params: {
prompt: "consent",
access_type: "offline",
response_type: "code"
}
}
})
]
}
export default NextAuth(authOptions)
</code></pre>
<h1>Error</h1>
<pre><code>https://next-auth.js.org/errors#jwt_session_error decryption operation failed {
message: 'decryption operation failed',
stack: 'JWEDecryptionFailed: decryption operation failed\n' +
' at gcmDecrypt (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/jose/dist/node/cjs/runtime/decrypt.js:67:15)\n' +
' at decrypt (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/jose/dist/node/cjs/runtime/decrypt.js:92:20)\n' +
' at flattenedDecrypt (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/jose/dist/node/cjs/jwe/flattened/decrypt.js:143:52)\n' +
' at async compactDecrypt (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/jose/dist/node/cjs/jwe/compact/decrypt.js:18:23)\n' +
' at async jwtDecrypt (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/jose/dist/node/cjs/jwt/decrypt.js:8:23)\n' +
' at async Object.decode (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/next-auth/jwt/index.js:66:7)\n' +
' at async Object.session (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/next-auth/core/routes/session.js:43:28)\n' +
' at async AuthHandler (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/next-auth/core/index.js:165:27)\n' +
' at async getServerSession (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/next-auth/next/index.js:159:19)\n' +
' at async unstable_getServerSession (/Users/sammadden/Documents/GitHub/sophs-next-app/node_modules/next-auth/next/index.js:195:10)\n' +
' at async handler (webpack-internal:///(api)/./pages/api/reviews/index.js:35:34)',
name: 'JWEDecryptionFailed'
}
</code></pre>
<p>Let me know if you need any more information.</p>
<p>I tried to secure an endpoint using <code>getServerSession(req, res, authOptions)</code>, but I kept receiving a JWT error.</p>
 

Latest posts

M
Replies
0
Views
1
MOHAMED AMIIN ABDI AADAN
M
Top