1

我正在学习 NextJS 和 NextAuth,并使用我自己的登录页面实现了 Credentials 登录,它在会话对象包含我的用户模型的地方工作(目前包含包括密码在内的所有内容,但显然它不会保持这种状态)。

我可以刷新页面并保持会话,但是如果我离开一两分钟然后刷新会话中的用户对象将成为默认设置,即使我的会话应该直到下个月才到期。

下面是我的 [...nextauth.tsx] 文件

import NextAuth, {NextAuthOptions} from 'next-auth'
import Providers from 'next-auth/providers'
import { PrismaClient } from '@prisma/client'
import {session} from "next-auth/client";

let userAccount = null;

const prisma = new PrismaClient();

const providers : NextAuthOptions = {
    site: process.env.NEXTAUTH_URL,
    cookie: {
        secure: process.env.NODE_ENV && process.env.NODE_ENV === 'production',
    },
    redirect: false,
    providers: [
        Providers.Credentials({
            id: 'credentials',
            name: "Login",
            async authorize(credentials : any) {
                const user = await prisma.users.findFirst({
                    where: {
                        email: credentials.email,
                        password: credentials.password
                    }
                });

                if (user !== null)
                {
                    userAccount = user;
                    return user;
                }
                else {
                    return null;
                }
            }
        })
    ],
    callbacks: {
        async signIn(user, account, profile) {
            console.log("Sign in call back");
            console.log("User Is");
            console.log(user);
            if (typeof user.userId !== typeof undefined)
            {
                if (user.isActive === '1')
                {
                    console.log("User credentials accepted")
                    return user;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                console.log("User id was not found so rejecting signin")
                return false;
            }
        },
        async session(session, token) {
            //session.accessToken = token.accessToken;
            if (userAccount !== null)
            {
                session.user = userAccount;
            }
            console.log("session callback returning");
            console.log(session);
            return session;
        },
        /*async jwt(token, user, account, profile, isNewUser) {
            console.log("JWT User");
            console.log(user);
            if (user) {
                token.accessToken = user.token;
            }
            return token;
        }*/
    }
}

const lookupUserInDb = async (email, password) => {
    const prisma = new PrismaClient()
    console.log("Email: " + email + " Password: " + password)
    const user = await prisma.users.findFirst({
        where: {
            email: email,
            password: password
        }
    });
    console.log("Got user");
    console.log(user);
    return user;
}

export default (req, res) => NextAuth(req, res, providers).

我从我的自定义表单触发登录,如下所示

signIn("credentials", {
            email, password, callbackUrl: `${window.location.origin}/admin/dashboard`, redirect: false }
        ).then(function(result){
            if (result.error !== null)
            {
                if (result.status === 401)
                {
                    setLoginError("Your username/password combination was incorrect. Please try again");
                }
                else
                {
                    setLoginError(result.error);
                }
            }
            else
            {
                router.push(result.url);
            }
            console.log("Sign in response");
            console.log(result);
        });

登录是从 next-auth/client 导入的

我的 _app.js 如下:

export default function Blog({Component, pageProps}) {
    return (
        <Provider session={pageProps.session}>
            <Component className='w-full h-full' {...pageProps} />
        </Provider>
    )

}

然后它在登录后重定向到的页面具有以下内容:(不确定这是否真的做除了获取活动会话之外的任何事情,所以我可以从前端引用它)

const [session, loading] = useSession()

当我登录时,[...nextauth.tsx] 中的会话回调返回以下内容:

session callback returning
{
  user: {
    userId: 1,
    registeredAt: 2021-04-21T20:25:32.478Z,
    firstName: 'Some',
    lastName: 'User',
    email: 'someone@example',
    password: 'password',
    isActive: '1'
  },
  expires: '2021-05-23T17:49:22.575Z'
}

npm run dev然后由于某种原因,从 PhpStorm 内部运行的终端然后输出

event - build page: /api/auth/[...nextauth]
wait  - compiling...
event - compiled successfully

但是我没有改变任何东西,即使我改变了,当然我对应用程序进行了更改,不应该触发会话被删除,但在此之后,会话回调然后返回以下内容:

session callback returning
{
  user: { name: null, email: 'someone@example.com', image: null },
  expires: '2021-05-23T17:49:24.840Z'
}

所以我有点困惑,似乎我的代码正在运行,但也许 PhpStorm 正在触发重新编译,然后会话被清除,但正如我上面所说,肯定会进行更改并且重新编译的版本不应该触发要修改的会话。

**更新 **

我做了一个测试,我做了一个构建并开始是一个生产版本,我可以尽可能多地刷新页面并且会话被维护,所以我证明我的代码工作正常。因此,看起来它与 PhpStorm 确定某些内容已更改并进行重新编译有关,即使没有任何更改。

4

1 回答 1

4

我终于找到了解决方案。

在提供者选项中,我添加了以下内容:

session: {
        jwt: true,
        maxAge: 30 * 24 * 60 * 60

    }

我将会话回调更改为以下内容:

async session(session, token) {
    //session.accessToken = token.accessToken;
    console.log("Session token");
    console.log(token);
    if (userAccount !== null)
    {
        session.user = userAccount;
    }
    else if (typeof token !== typeof undefined)
    {
        session.token = token;
    }
    console.log("session callback returning");
    console.log(session);
    return session;
}

jwt 回调如下:

async jwt(token, user, account, profile, isNewUser) {
    console.log("JWT Token User");
    console.log(token.user);
    if (typeof user !== typeof undefined)
    {
         token.user = user;
    }
    return token;
}

基本上我误解了我需要使用 jwt 回调,并且在第一次调用此回调时,使用了从 signIn 回调设置的用户模型,因此我可以将其添加到令牌中,然后可以将其添加到会话中会话回调。

对 jwt 的后续请求中的问题是,未设置用户参数,因此我将令牌用户对象设置为未定义,这就是我的会话被空白的原因。

我不明白为什么在将它作为生产版本运行时我似乎没有得到这种行为。

于 2021-04-24T21:36:46.480 回答