使用JWT在Cookie中,Google OAuth,Passport和React

问题描述

我正在Node / Express服务器中使用Passport和Google OAuth来验证我的React应用。我遇到的问题是我不知道如何将Google回调重定向到前端,因为当我执行设置的cookie(包含身份验证令牌)时,它们就会消失。我可以看到已设置cookie,但是随后通过Node回调进行的重定向刷新了页面,它们消失了。

在向您展示代码之前,值得一提的是这是通过localhost完成的,因此这可能是cookie无法持久的原因,但这对我来说没有意义,因为我可以看到它们已在其中设置第一名。

这是我的路线处理程序:

this.router.get(
      `${this.path}/google`,passport.authenticate("google",{
        scope: ["profile","email"],session: false,})
    );
    this.router.get(
      `${this.path}/google/callback`,{ session: false }),this.googleOAuth
    );

This.path是/ auth。然后,处理程序本身:

 private initializeGoogleStrategy() {
    passport.use(
      new GoogleStrategy(
        {
          clientID: process.env.GOOGLE_CLIENT_ID,clientSecret: process.env.GOOGLE_CLIENT_SECRET,callbackURL: `${this.path}/google/callback`,},async (accesstoken,refreshToken,profile,done) => {
          try {
            const existingUser: IUser = await this.user.findOne({
              "google.id": profile.id,});
            if (existingUser) {
              // we don't need to do anything
              return done(null,existingUser);
            }

            const newUserByGoogle = await this.user.create({
              method: LoginMethods.google,google: {
                id: profile.id,email: profile.emails[0].value,});
          } catch (error) {
            done(error,false,error.message);
          }
        }
      )
    );
  }

private googleOAuth = async (
    request: express.Request,response: express.Response,next: express.NextFunction
  ) => {
    this.createtokenAndAttach(request.user,response);
// as soon as this redirect happens the cookie in the browser disappears

    response.redirect("/");
  };

  private createtoken(user: IUser): TokenData {
    const expiresIn = 60 * 60; // an hour
    const secret = process.env.JWT_SECRET;
    const dataStoredInToken: DataStoredInToken = {
      _id: user._id,};
    return {
      expiresIn,token: jwt.sign(dataStoredInToken,secret,{ expiresIn }),};
  }

  private createtokenAndAttach(user: IUser,response: express.Response) {
    const tokenData = this.createtoken(user);
    response.setHeader("Set-Cookie",[this.createCookie(tokenData)]);
  }

在事情的反应方面,我正在使用如下所示的代理服务器:

const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
  app.use(
    ["/auth/google","/auth/current_user"],createProxyMiddleware({
      target: "http://localhost:5000",})
  );
};

我的React应用正在localhost:3000上运行。

我这样做是为了触发React应用程序中的回调:

  <>
    <h1> I'm the landing page</h1>
    <a href="/auth/google">Click this</a>
  </>
);

我想发生的事情是,当用户单击链接时,他们通过google进行身份验证,这会调用回调,并简单地将React应用程序设置为/并设置cookie。

发生的是,当用户单击链接并进行身份验证时,设置了带有令牌的cookie,但随后重定向刷新了页面,cookie消失了。

如果有什么我想念的,我将非常感谢您的帮助。

非常感谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)