如何解决NextAuth 授权用户但用户信息为空
我正在尝试使用凭据(电子邮件和密码)实施 NextAuth。
我已经为此设置了我的 mongodb。我还设置了 /api/proile/
路由来发布登录凭据并使用 Postman 对其进行测试,正确返回用户。
但是问题始于登录后。当我登录时,凭据在 vscode 终端中返回(我使用 /api/auth/[...nextauth].js
控制台登录 console.log(credentials)
但在浏览器中它授权用户,我可以访问和查看受保护的路由和内容,但是当我在前端登录会话时,它显示为 null
用户信息,如下图所示;
这是我的 /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);
顺便说一句,当我使用静态用户凭据时,就像我在上面的代码中所评论的那样,它工作得非常好并正确返回会话信息...
还有我的/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
部分。现在它工作正常
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。