Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 492
Евгений Скореев Avatar asked Oct 29 '20 08:10

Евгений Скореев


2 Answers

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

like image 101
codabool Avatar answered Oct 19 '22 06:10

codabool


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'}
like image 1
Chima Avatar answered Oct 19 '22 07:10

Chima