如何在 Next.js 中使用 next-auth 实现凭据授权?

Posted

技术标签:

【中文标题】如何在 Next.js 中使用 next-auth 实现凭据授权?【英文标题】:How to implement credentials authorization in Next.js with next-auth? 【发布时间】:2021-02-11 15:46:49 【问题描述】:

我尝试使用next-auth 获取凭据身份验证,但我没有使用它的经验,无论我做什么,我都会收到以下消息:

[next-auth][error][callback_credentials_jwt_error] 仅当启用 JSON Web 令牌时才支持使用凭据登录 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,
    ,

我不知道我做错了什么。

【问题讨论】:

【参考方案1】:

尝试将此添加到您的 [...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

【讨论】:

可以确认这是正确的,session jwt: true 需要设置。【参考方案2】:

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,
,

【讨论】:

以上是关于如何在 Next.js 中使用 next-auth 实现凭据授权?的主要内容,如果未能解决你的问题,请参考以下文章

Next.js/Next-Auth/Apollo/GraphQL 设置

使用 Next-Auth 进行身份验证时如何修复内部服务器错误

next-auth 中 useSession() 的“加载”返回值是啥?

为啥切换语言环境时我的会话没有加载?

Next js:next auth provider + redux provider

登录后在哪里以及如何更改会话用户对象?