我正在学习NextAuth,我只是尝试在API中获取我当前的会话。从文档中看上去很容易,但是它总是给我null。但是,如果我从客户端使用useSession,就会得到当前会话。我做错了什么?
import { getSession } from 'next-auth/react';
const handler = nc().use(Cors());
handler.post(async (req, res) => {
if (req.method === 'POST') {
const session = await getSession({ req });
if (session) {
console.log('Session', JSON.stringify(session, null, 2));
} else {
console.log('Not authenticated.');
res.status(401);
}
res.end();发布于 2022-05-10 19:30:09
我花了很多时间去理解这个问题。解决办法可以是以下办法之一:
如果下一个auth服务器无法访问env NEXTAUTH_URL中定义的规范URL (就像无法从nextjs服务器主机访问https://example.com ),则必须将另一个env var定义为localhost (映射到nextJS服务器主机或nextJS容器):NEXTAUTH_URL_INTERNAL=http://localhost:<your nextJS host port>。
检查:https://next-auth.js.org/v3/configuration/options#nextauth_url_internal。这个var将设置下一个auth服务器端操作来执行localhost (这是有意义的,因为getServerSideProps()从nextJS调用getSession()将调用localhost操作,不需要路由到外部)。
如果设置内部var没有解决,可能是安全cookie (HTTPS)造成的。在authoptions{} set useSecureCookies: false,中:这将告诉next-auth永远不要将cookie设置为仅限于安全站点(HTTPS)。
https://stackoverflow.com/questions/69538112
复制相似问题