Как реализовать авторизацию учетных данных в Next.js с помощью next-auth?

Я пытаюсь получить авторизацию учетных данных с помощью next-auth, но у меня нет опыта его использования, и что бы я ни делал, я получаю следующее сообщение:[next-auth][error][callback_credentials_jwt_error] Signin in with credentials is only supported if JSON Web Tokens are enabled https://next-auth.js.org/errors#callback_credentials_jwt_error . Возможно, в результате получился беспорядок, но я надеюсь, что вы мне поможете.

Это мой файл src/pages/api/auth/[...nextauth].js.

import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
import User from "@models/User"

const options = {
    NEXTAUTH_URL:process.env.NEXTAUTH_URL,
    providers: [
        Providers.Credentials({
            // The name to display on the sign in form (e.g. 'Sign in with...')
            name: 'Avista',
            // The credentials is used to generate a suitable form on the sign in page.
            // You can specify whatever fields you are expecting to be submitted.
            // e.g. domain, username, password, 2FA token, etc.

            credentials: {
                email: {label: "Email", type: "text"},
                password: {label: "Password", type: "password"}
            },

            authorize: async (credentials) => {
                // Add logic here to look up the user from the credentials supplied
                // const user = {id: 1, name: 'J Smith', email: 'jsmith@example.com'}
                const user = await User.findOne()
                console.log("Данные входа", credentials)

                if (user) {
                    // Any object returned will be saved in `user` property of the JWT
                    return Promise.resolve(user)
                } else {
                    // If you return null or false then the credentials will be rejected
                    return Promise.resolve(null)
                    // You can also Reject this callback with an Error or with a URL:
                    // return Promise.reject(new Error('error message')) // Redirect to error page
                    // return Promise.reject('/path/to/redirect')        // Redirect to a URL
                }
            }
        }),
        Providers.Email({
            server: {
                host: process.env.EMAIL_SERVER_HOST,
                port: process.env.EMAIL_SERVER_PORT,
                auth: {
                    user: process.env.EMAIL_SERVER_USER,
                    pass: process.env.EMAIL_SERVER_PASSWORD
                }
            },
            from: process.env.EMAIL_FROM
        }),
    ],

    // A database is optional, but required to persist accounts in a database
    database: process.env.MONGO_URI,
    secret: process.env.JWT_SIGNING_PRIVATE_KEY,
    },
}

Я не знал, что делаю не так. Я могу получить больше информации по этой теме.

3 ответа

Попробуйте добавить это на свою страницу [...nextauth].js

         session: {
    jwt: true, 
    // Seconds - How long until an idle session expires and is no longer valid.
    maxAge: 30 * 24 * 60 * 60, // 30 days
  },

подробнее о вариантах читайте здесь: https://next-auth.js.org/configuration/options#jwt

Это может быть полезно для кого-то еще.

Вам нужно указать, что вы хотите использовать стиль авторизации jwt. Делатьoptions.sessionбыть:

      { jwt: true }

Если вы используете версию next-auth 4, вам следует вместо этого сделать:

      { strategy: 'jwt'}

Добавьте это после providers: []

      callbacks: {
    jwt: async ({ token, user }) => {
        user && (token.user = user)
        return token;
    },
    session: async ({ session, token }) => {
        session.user = token.user
        return session;
    }

},
secret: "secret",
jwt: {
    secret: "ksdkfsldferSDFSDFSDf",
    encryption: true,
},
Другие вопросы по тегам