首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当我使用Passport和谷歌oauth2集成登录时,如何重定向

当我使用Passport和谷歌oauth2集成登录时,如何重定向
EN

Stack Overflow用户
提问于 2020-11-25 20:16:41
回答 1查看 113关注 0票数 0

我有以下代码,登录工作,但在选择一个谷歌帐户后,它仍然加载,并没有导致callbackURL的网址,我已经指出。

/pages/api/auth/google/index.js

代码语言:javascript
复制
import nextConnect from "next-connect";
import passport from "passport";
import { Strategy as GoogleStrategy } from "passport-google-oauth20";

const authenticate = (method, options, req, res) =>
  new Promise((resolve, reject) => {
    passport.authenticate(method, options, (error, token) => {
      if (error) {
        reject(error);
      } else {
        resolve(token);
      }
    })(req, res);
  });

passport.use(
  new GoogleStrategy(
    {
      clientID: process.env.GOOGLE_CLIENT,
      clientSecret: process.env.GOOGLE_SECRET,
      callbackURL: "http://localhost:3000/api/auth/google/redirect",
      passReqToCallback: true,
    },
    (req, accessToken, refreshToken, profile, done) => {
      console.log(profile);
    }
  )
);

export default nextConnect()
  .use(passport.initialize())
  .get(async (req, res) => {
    try {
      await authenticate("google", { scope: ["profile", "email"] }, req, res);
    } catch (error) {
      console.log(error);
      res.end(JSON.stringify({ error: error.message }));
    }
  });

/pages/api/auth/google/redirect.js

代码语言:javascript
复制
import nextConnect from "next-connect";
import passport from "passport";

export default nextConnect().get(
  passport.authenticate("google"),
  (req, res) => {
    res.writeHead(302, {
      Location: "/",
    });
    res.end();
  }
);
EN

回答 1

Stack Overflow用户

发布于 2020-11-27 23:17:52

尝试通过以下方式更改路由:如果登录失败,用户将被重定向至/login页面,否则将被重定向至首页/

代码语言:javascript
复制
export default nextConnect().get(
  passport.authenticate('google', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  }
);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65004556

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档