Boa*_*rdy 4 session credentials phpstorm next.js next-auth
我正在学习 NextJS 和 NextAuth,并使用我自己的登录页面实现了凭据登录,并且它正在会话对象包含我的用户模型的地方工作(目前包含包括密码在内的所有内容,但显然它不会保持这样)。
我可以刷新页面并维持会话,但是如果我离开一两分钟然后刷新会话中的用户对象将成为默认值,即使我的会话应该到下个月才会过期。
下面是我的 [...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).
Run Code Online (Sandbox Code Playgroud)
我从自定义表单触发登录,如下所示
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);
});
Run Code Online (Sandbox Code Playgroud)
登录是从 next-auth/client 导入的
我的 _app.js 如下:
export default function Blog({Component, pageProps}) {
return (
<Provider session={pageProps.session}>
<Component className='w-full h-full' {...pageProps} />
</Provider>
)
}
Run Code Online (Sandbox Code Playgroud)
然后,登录后重定向到的页面如下:(不确定这除了获取活动会话之外是否真的执行其他操作,以便我可以从前端引用它)
const [session, loading] = useSession()
Run Code Online (Sandbox Code Playgroud)
当我登录时,[...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'
}
Run Code Online (Sandbox Code Playgroud)
npm run dev然后由于某种原因,从 PhpStorm 内部运行的终端输出
event - build page: /api/auth/[...nextauth]
wait - compiling...
event - compiled successfully
Run Code Online (Sandbox Code Playgroud)
但我没有改变任何东西,即使我做了,我肯定对应用程序进行了更改,不应该触发会话被删除,但在此之后,会话回调会立即返回以下内容:
session callback returning
{
user: { name: null, email: 'someone@example.com', image: null },
expires: '2021-05-23T17:49:24.840Z'
}
Run Code Online (Sandbox Code Playgroud)
所以我有点困惑,看起来也许我的代码正在工作,但也许 PhpStorm 正在触发重新编译,然后会话被清除,但正如我上面所说,肯定会进行更改,并且重新编译的版本不应触发要修改的会话。
我做了一个测试,我进行了构建并启动了生产版本,我可以根据需要刷新页面并保持会话,所以我证明了我的代码工作正常。所以看起来这与 PhpStorm 确定某些内容已更改并重新编译有关,即使没有任何更改。
我终于找到了解决方案。
对于提供者选项,我添加了以下内容:
session: {
jwt: true,
maxAge: 30 * 24 * 60 * 60
}
Run Code Online (Sandbox Code Playgroud)
我将会话回调更改为以下内容:
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;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
基本上我误解了我需要使用 jwt 回调,并且在第一次调用此回调时,使用从登录回调设置的用户模型,因此我可以将其添加到令牌中,然后将其添加到会话中会话回调。
对 jwt 的后续请求中的问题是,用户参数未设置,因此我将令牌用户对象设置为未定义,这就是我的会话被清空的原因。
我不明白为什么我在将其作为生产版本运行时似乎没有得到该行为。
| 归档时间: |
|
| 查看次数: |
16506 次 |
| 最近记录: |