NextAuth 与自定义凭据提供程序不创建会话
Posted
技术标签:
【中文标题】NextAuth 与自定义凭据提供程序不创建会话【英文标题】:NextAuth with custom Credential Provider Not creating session 【发布时间】:2021-01-22 09:56:34 【问题描述】:我正在尝试在我的 NextJs 应用中实现 NextAuth。我正在关注官方文档。但出于某种原因,似乎用户会话对象不是在登录时生成的。
这是我的 pages/api/auth/[...nextauth].js 文件中的代码
import NextAuth from "next-auth";
import Providers from "next-auth/providers";
import axios from "axios";
export default (req, res) =>
NextAuth(req, res,
providers: [
Providers.Credentials(
id: 'app-login',
name: APP
authorize: async (credentials) =>
console.log("credentials_:", credentials);
try
const data =
username: credentials.username,
password: credentials.password
// API call associated with authentification
// look up the user from the credentials supplied
const user = await login(data);
if (user)
// Any object returned will be saved in `user` property of the JWT
return Promise.resolve(user);
catch (error)
if (error.response)
console.log(error.response);
Promise.reject(new Error('Invalid Username and Password combination'));
,
),
],
site: process.env.NEXTAUTH_URL || "http://localhost:3000",
session:
// Use JSON Web Tokens for session instead of database sessions.
// This option can be used with or without a database for users/accounts.
// Note: `jwt` is automatically set to `true` if no database is specified.
jwt: true,
// Seconds - How long until an idle session expires and is no longer valid.
maxAge: 1 * 3 * 60 * 60, // 3 hrs
// Seconds - Throttle how frequently to write to database to extend a session.
// Use it to limit write operations. Set to 0 to always update the database.
// Note: This option is ignored if using JSON Web Tokens
updateAge: 24 * 60 * 60, // 24 hours
,
callbacks:
// signIn: async (user, account, profile) => return Promise.resolve(true) ,
// redirect: async (url, baseUrl) => return Promise.resolve(baseUrl) ,
// session: async (session, user) => return Promise.resolve(session) ,
// jwt: async (token, user, account, profile, isNewUser) => return Promise.resolve(token)
,
pages:
signIn: '/auth/credentials-signin',
signOut: '/auth/credentials-signin?logout=true',
error: '/auth/credentials-signin', // Error code passed in query string as ?error=
newUser:'/'
,
debug: process.env.NODE_ENV === "development",
secret: process.env.NEXT_PUBLIC_AUTH_SECRET,
jwt:
secret: process.env.NEXT_PUBLIC_JWT_SECRET,
);
const login = async data =>
var config =
headers:
'Content-Type': "application/json; charset=utf-8",
'corsOrigin': '*',
"Access-Control-Allow-Origin": "*"
;
const url = remote_user_url;
const result = await axios.post(url, data, config);
console.log('result', result);
return result;
;
我在这里没有得到什么?感谢您的帮助。
【问题讨论】:
你能分享一下登录页面的代码,里面有登录表单以及注销是如何工作的吗? 【参考方案1】:我最终设法解决了这个问题。由于为自定义凭据提供程序指定了 'id' 和 'name' 选项,出现问题
我已经删除了它们,代码现在可以工作了。
【讨论】:
您能分享一下登录页面代码以及退出的工作原理吗? 大声笑,我花了一整天的时间试图找出同样的问题,但就是这么简单。现在它正在工作,但为什么/那些id
和name
在这里起作用?以上是关于NextAuth 与自定义凭据提供程序不创建会话的主要内容,如果未能解决你的问题,请参考以下文章
NextJS 和 NextAuth 会话用户对象由于 [...nextauth.ts] 被触发重新编译而丢失