How to implement credentials authorization in Next.js with next-auth?
Asked Answered
D

3

9

I try to get credentials auth with next-auth, but I have no experience to use it and whatever I do, i get following message:

[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

This is my src/pages/api/auth/[...nextauth].js file.

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: '[email protected]'}
                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,
    },
}

I don't know what I do wrong.

Deliberate answered 29/10, 2020 at 8:0 Comment(0)
S
12

try adding this to your [...nextauth].js page

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

read more about the options here: https://next-auth.js.org/configuration/options#jwt

Sopher answered 29/10, 2020 at 19:57 Comment(1)
Can confirm this is correct, session { jwt: true } needs to be set.Hedvige
E
2

This might be useful for someone else.

You need to specify that you want to use the jwt auth style. Make options.session to be:

{ jwt: true }

If you using next-auth version 4, you should instead do:

{ strategy: 'jwt'}
Euphonize answered 15/10, 2022 at 23:57 Comment(0)
R
0

Add this after 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,
},
Rim answered 15/2, 2022 at 8:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.