gpt4 book ai didi

node.js - NextAuth 授权用户但用户信息为空

转载 作者:行者123 更新时间:2023-12-05 05:59:55 24 4
gpt4 key购买 nike

我正在尝试使用凭据(电子邮件和密码)实现 NextAuth。
我已经为此设置了我的 mongodb。我还设置了 /api/proile/ 路由来发布登录凭据并使用 Postman 对其进行了测试,正确返回了用户。


但问题是在登录后开始的。当我登录时,凭证在 vscode 终端中返回(我控制台登录 /api/auth/[...nextauth].jsconsole.log(credentials) 但在浏览器中它授权用户,我可以访问和查看 protected 路由和内容,但是当我在前端记录 session 时,它显示为 null为用户信息,如下图所示;
consolelog1

这是我的 /api/auth/[...nextauth].js 代码;

import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';
import { connectToDatabase } from '../../../util/mongodb';

const options = {
providers: [

Providers.Credentials({
name: 'Credentials',
credentials: {
email: { label: 'Email', type: 'text' },
password: { label: 'Password', type: 'password' },
},
async authorize(credentials, req) {
console.log(credentials);
const res = await fetch('http://localhost:3000/api/profile/', {
method: 'POST',
body: JSON.stringify(credentials),
headers: {
'Content-Type': 'application/json',
},
});
const user = await res.json();

// const user = { id: '1', name: 'Suat Bayrak', email: 'test@test.com2' };

if (user) {
return user;
} else {
return null;
}
},
}),
],
pages: {
signIn: '/signin',
},
session: {
jwt: true,
maxAge: 30 * 24 * 60 * 60,
updateAge: 24 * 60 * 60,
},


database: `mongodb+srv://${process.env.MONGO_DB_USERNAME}:${process.env.MONGO_DB_PASSWORD}@nextjs-academia- sb.ki5vd.mongodb.net/test`,
};

export default (req, res) => NextAuth(req, res, options);

顺便说一句,当我像我在上面的代码中评论的那样使用静态用户凭据时,它工作得很好并且正确地返回 session 信息......

这也是我的 /pages/signin.js

import { signIn } from 'next-auth/client';
import { useState } from 'react';
import { useRouter } from 'next/router';

export default function SignIn() {
const router = useRouter();

const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loginError, setLoginError] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();

console.log('submitted!');
signIn('credentials', {
email: email,
password: password,
// email: 'test@test.com',
// password: '1234',
callbackUrl: 'http://localhost:3000/about',
redirect: false,
}).then(function (result) {
console.log(result);
if (result.error !== null) {
if (result.status === 401) {
setLoginError(
'Your username/password combination was incorrect. Please try again'
);
} else {
setLoginError(result.error);
}
} else {
console.log(result);
router.push(result.url);
}
});
};

return (
<form onSubmit={handleSubmit}>
<label>
Email
<input
name='email'
type='text'
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</label>
<label>
Password
<input
name='password'
type='password'
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</label>
<button type='submit'>Sign in</button>
</form>
);
}

这也是我的整个代码的 github 存储库; GitHub Repo

更新:第一次登录时,用户信息显示在终端上,但在我刷新页面后,它显示 undefined

最佳答案

import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';

const options = {
providers: [

Providers.Credentials({
name: 'Credentials',
credentials: {
email: { label: 'Email', type: 'text' },
password: { label: 'Password', type: 'password' },
},
async authorize(credentials, req) {
console.log(credentials);
let user;

const res = await fetch('http://localhost:3000/api/profile/', {
method: 'POST',
body: JSON.stringify(credentials),
headers: {
'Content-Type': 'application/json',
},
});
const arrayToJson = await res.json();
user = arrayToJson[0];

if (user) {
return user;
} else {
return null;
}
},
}),
],
pages: {
signIn: '/signin',
},
session: {
jwt: true,
maxAge: 30 * 24 * 60 * 60,
updateAge: 24 * 60 * 60,
},
callbacks: {
async signIn(user) {
return user.userId && user.isActive === '1';
},
async session(session, token) {
session.user = token.user;
return session;
},
async jwt(token, user) {
if (user) token.user = user;
return token;
},
},

database: `mongodb+srv://${process.env.MONGO_DB_USERNAME}:${process.env.MONGO_DB_PASSWORD}@nextjs-academia-sb.ki5vd.mongodb.net/test`,
};

export default (req, res) => NextAuth(req, res, options);

所以问题出在代码的 callbacks 部分。现在它工作正常

关于node.js - NextAuth 授权用户但用户信息为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67901907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com