Oauth2 Google 身份验证流程 - Next.JS/Express [英] Oauth2 Google Authentication flow - Next.JS / Express

查看:23
本文介绍了Oauth2 Google 身份验证流程 - Next.JS/Express的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 React/Next.Js 前端,并尝试使用 Google 的 Oauth2 策略实现身份验证.

I am using a React/Next.Js Frontend and am trying to implement authentication with the Oauth2 strategy with Google.

我对这个过程很困惑.

目前在客户端上,我有一个 Google 登录组件,其中包含一个客户端 ID,并且可以检索访问令牌.

Currently on the client, I have a Google sign in component that has a Client ID with in it and can retrieve an access token.

      <GoogleLogin
            clientId="myclientid"
            buttonText="Login"
            onSuccess={userLogin}
            onFailure={userLogin}
            cookiePolicy={'single_host_origin'}
  />

然后我有一个函数,它在成功时使用访问令牌向我的后端发送一条发布消息,例如:

I then have a function, which on success sends a post message to my backend with an access token, such as this:

export function googleAuthenticate(accessToken : string) : any{
    axios({
        method: 'post',
        url: "http://localhost:4000/auth/google",
        data: {
          accessToken: accessToken
        }
      })
    .then(res => {
        console.log(res);
    })
    .catch(err => {
        console.log("Failure!");
        console.log(err);
    })
};

在后端我使用的是护照,路线如下所示:

On the backend I am using passport, and the routes look like this:

import express from 'express';
import passport from 'passport';
import Logger from '../logger/index';

const router = express.Router();

export function isAuthenticated(req:express.Request, res:express.Response, next : any) {
    return req.isAuthenticated() ?
        next() :
        res.sendStatus(401);
 }  

  router.get('/fail', (_req:express.Request, res:express.Response) => {
    res.json({ loginFailed: true });
  });

  router.post('/google', passport.authenticate('google', { scope: ['profile']}), (_req:express.Request, _res:express.Response) => {
    Logger.info("GET Request at Google Authentication endpoint received.");
  });

  router.get(
    '/google/callback',
    passport.authenticate('google', { failureRedirect: '/login' }),
    (_req:express.Request, res:express.Response) => {
      res.redirect('/graphql');
    }
  );

export default router;

我的护照模块如下所示:

My passport module looks like this:

module.exports = function(passport : any, GoogleStrategy : any){
  passport.use(new GoogleStrategy({
    clientID: config.google.client_id,
    clientSecret: config.google.client_secret,
    callbackURL: config.google.redirect_url
  },
  function(accessToken : string, profile : Profile, refreshToken : string, cb : any) {
    return cb(null, {
      id: profile.googleId,
      username: profile.email,
      image: profile.imageUrl,
      firstName: profile.givenName,
      surname: profile.familyName,
      accessToken: accessToken,
      refreshToken: refreshToken
    })
  }
  ));
}

由于 Next.js 是服务器端渲染,我无法使用保存令牌.我知道我必须使用 cookie.但这是如何工作的?我无法从快速后端重定向客户端浏览器.

Since Next.js is a server side rendered, I am not able to use save a token. I understand I have to use a cookie. But how does this work? I cannot redirect the client browser from the express backend.

目前我只看到这两个错误:

Currently I'm just seeing these 2 errors:

OPTIONS https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A4000%2localhost:3000%2Fdashboard&scope=profile&client_id=687602672235-l0uocpfchbjp34j1jjlv8tqv7jadb8og.apps.googleusercontent.com 405

Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A4000%2Fbackoffice.dev.myos.co%2Fdashboard&scope=profile&client_id=687602672235-l0uocpfchbjp34j1jjlv8tqv7jadb8og.apps.googleusercontent.com' (redirected from 'http://localhost:4000/auth/google') from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

推荐答案

你可以使用 NextAuth.js 为您处理此问题.为了测试 localhost,您应该使用 ngrok 将您的 localhost 服务器暴露给网络并在 google 平台中配置给定的 url

You could use NextAuth.js to handle this for you. In order to test localhost you should use ngrok to expose your localhost server to the web and configure the given url in google platform

这篇关于Oauth2 Google 身份验证流程 - Next.JS/Express的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆