chrome扩展-通过后端express服务器进行oauth身份验证

xdnvmnnf  于 2021-10-10  发布在  Java
关注(0)|答案(0)|浏览(225)

我构建了一个web应用程序,它有一个后端express服务器,可以通过passport处理oauth身份验证。
我现在正在尝试构建一个附带的浏览器扩展,它将通过express服务器与web应用程序共享一个会话。
我有一种方法似乎很管用,那就是在一个新窗口中打开web应用程序的oauth流。从技术上讲,身份验证是通过web应用程序完成的,但是扩展最终能够从服务器获取身份验证状态,所以这“起作用”。

const signIn= () => {
chrome.windows.create({
  url: "http://localhost:3000/auth/google-ext",
});

};
我不喜欢这个解决方案,因为它最小化了扩展。
我已经尝试使用chrome.identity.launchwebauthflow执行以下操作,并调用我将从webapp使用的相同oauth端点。

chrome.identity.launchWebAuthFlow(
  {
    url: "http://localhost:5000/auth/google-ext",
    interactive: true,
  },
  (responseUrl) => {
    fetchUser();
  }
);

这将打开oauth登录页面,但在尝试登录后,在扩展端出现以下错误:
未选中的runtime.lasterror:无法加载授权页。
在我的服务器上,我得到一个
令牌错误:未经授权
以下是我的快速路线和护照策略:
注意:当使用windows.create方法时,我会使用我的web应用程序的google客户端id。对于launchwebauthflow方法,我使用我的google扩展客户端id(web应用程序和扩展都在同一个google项目下)。

// Extension specific routes
    router.get(
      "auth/google-ext",
      passport.authenticate("google-ext", {
        scope: ["profile", "email"],
      })
    );

    router.get(
      "auth/google-ext/callback",
      passport.authenticate("google-ext", {
        failureFlash: true,
      }),
      (req, res) => {
        res.redirect("https://<app-id>.chromiumapp.org/");
      }
    );

    // passport.js
    passport.use(
      "google-ext",
      new GoogleStrategy(
        {
          clientID: googleExtensionClientID,
          clientSecret: googleClientSecret,
          callbackURL: "/auth/google-ext/callback",
          proxy: true,
        },
        async (accessToken, refreshToken, profile, done) => {
          const existingUser = await User.findOne({ googleId: profile.id });

          if (existingUser) {
            return done(null, existingUser);
          }

          const user = await new User({
            name: profile.name,
            email: profile.emails[0].value,
            googleId: profile.id,
          }).save();
          done(null, user);
        }
      )
    );

我想弄明白这件事已经有一段时间了,但一直没能弄明白。我想做的是可能的吗?我必须使用谷歌的getauthtoken吗?
编辑:
如果我在passport策略中使用我的web应用程序客户端id,oauth流正常工作,并且我的/auth/google ext/callback接收到一个 req.user . 但是,会话似乎没有保存在任何地方,即,检索会话的后续请求 req.user 结果为空/未定义。
这是我的服务器 index.js ```
const app = express();

app.use(
cors({ origin: "chrome-extension://" })
);

app.use(express.json());

app.use(
cookieSession({
maxAge: 30 * 24 * 60 * 60 * 1000,
keys: [cookieKey],
})
);
app.use(passport.initialize());
app.use(passport.session());

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题