使用 nextAuth 对外部 API 进行身份验证 (nestJS)

Use nextAuth to authenticate an external api (nestJS)

提问人:Dan Lincoln 提问时间:6/29/2023 更新时间:6/29/2023 访问量:231

问:

我正在设置一个带有 nextjs 前端和 nestjs 后端的本地 monorepo,使用 nextauth 通过 google 进行身份验证。

我能够仅使用 nextjs app/api 路由登录并获取会话,并且我可以使用 在 nextJS 后端验证会话,所以我相信我的配置是正确的。getServerSession

但是,当我从页面直接向 nestjs 后端发送请求时,我无法在身份验证防护中验证会话。这可能吗?

NextJS 在本地端口 3000 上提供服务,Nest 在 8080 上提供服务

网页/页面/api/auth/[...nextauth.ts]

export const authOptions: NextAuthOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env["GOOGLE_ID"] ?? "",
      clientSecret: process.env["GOOGLE_SECRET"] ?? "",
    }),
  ],
}

export default NextAuth(authOptions)

api/src/auth-guard.ts

import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
import { getServerSession } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
@Injectable()
export class AuthGuard implements CanActivate {
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const req = context.switchToHttp().getRequest();
    const res = context.switchToHttp().getResponse();

    const session = await getServerSession(req, res, {
      providers: [
        GoogleProvider({
          clientId: process.env["GOOGLE_ID"] ?? "",
          clientSecret: process.env["GOOGLE_SECRET"] ?? "",
        }),
      ],
    });

    return !!session;
  }
}

网页/页面/profile/index.tsx

import { signOut } from "next-auth/react";
import { Button } from "@chakra-ui/react";
import { useEffect } from "react";
import axios from "axios";

export default function ProfilePage() {
  useEffect(() => {
    const fetchthings = async () => {
      await axios.get("http://localhost:8080/gym", {
        withCredentials: true
      });
    };

    fetchthings();
  }, []);

  return (
    <div>
      profile
      <Button
        onClick={() =>
          signOut({
            callbackUrl: "/",
          })
        }
      >
        Log out
      </Button>
    </div>
  );
}

API/main.ts(嵌套)

import { Logger } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.enableShutdownHooks();


  app.enableCors({
    origin: "http://localhost:3000",
    credentials: true,
  });

  await app.listen(8080);

  Logger.log(`🚀 Application is running on: ${await app.getUrl()}`);
}

bootstrap().catch((ex) => {
  console.error(ex);
});
node.js reactjs next.js nestjs next-auth

评论

0赞 Igor Danchenko 6/29/2023
不同的端口 === 没有会话 cookie。查看开发工具中的请求标头。

答: 暂无答案