NextAuth CredentialsProvider登录成功后user返回null及跳转异常问题
问题1:登录/登出跳转到http://localhost:5400的解决方法
- 首先在项目根目录的
.env环境变量文件中添加配置:NEXTAUTH_URL=http://localhost:3000,next-auth默认会读取这个地址作为所有重定向、回调的根域名,未配置时会误读取请求的后端地址导致跳转错误。 - 登出时可手动指定回调地址避免跳转异常:
<button onClick={() => signOut({ callbackUrl: 'http://localhost:3000/home' })}>SignOut</button> - 若不需要登录时自动跳转,可在
signIn参数中添加redirect: false,自行处理登录后的逻辑:signIn('credentials', { email: 'mohdfathi_mhdnoor@yahoo.com', password: 'qwer1234', callbackUrl: `${window.location.origin}/about`, redirect: false }).then(res => { if(res.ok) window.location.href = res.url })
问题2:登录成功后session中user字段全为null的解决方法
这个问题是两个原因共同导致的:
authorize方法返回的用户对象格式不符合默认要求,且没有包含email、name等默认字段- 未配置自定义回调将后端返回的用户字段同步到jwt和session中
修改[...nextauth].js配置如下:
import axios from 'axios' import NextAuth from 'next-auth' import Providers from 'next-auth/providers' import { config } from '../../../src/utils/Header' export default NextAuth({ // 指定session使用jwt策略,credentials提供者默认不支持数据库session session: { strategy: 'jwt' }, providers: [ Providers.Credentials({ name: 'Portfolio V4 Credentials', credentials: { email: { label: "Email", type: "email", placeholder: "Please enter an email" }, password: { label: "Password", type: "password", placeholder: "Please enter a password" } }, async authorize(credentials, req) { try { const res = await axios.post( process.env.REACT_APP_SERVER_ENDPOINT_HOST + "/api/auth/callback/credentials", { uid: '', email: credentials.email, password: credentials.password }, config ) const user = await res if (user.data.success) { // 直接返回用户信息对象,同时把email手动加上(后端返回没有该字段的情况下) return { ...user.data.data, email: credentials.email } } return null } catch (e) { console.log('Error: ') console.log(e) return null } } }) ], // 新增回调配置,同步用户信息到jwt和session callbacks: { async jwt({ token, user }) { // 登录成功时user存在,将用户字段存入token if (user) { token.uid = user.uid token.sato = user.sato token.email = user.email } return token }, async session({ session, token }) { // 将token中存储的用户字段同步到session返回给前端 session.user.uid = token.uid session.user.sato = token.sato session.user.email = token.email return session } } })
修改完成后重启项目即可正常读取session中的用户信息。
内容的提问来源于stack exchange,提问作者lala
相关产品推荐
相关产品推荐

