reactjs 在react-google-login上使用uxMode=“重定向”时获取访问令牌

jjjwad0x  于 2023-02-08  发布在  React
关注(0)|答案(1)|浏览(147)

我使用'react-google-login'。我需要发送access_token到后端,当我使用uxMode=“popup”时,onSuccess函数被调用,所以我可以从响应中获得access_token。
但是我想使用uxMode=“redirect”,下面是我的代码:

<GoogleLogin
              clientId="..."
              buttonText="go to sign in"
              onSuccess={::this.responseGoogle}
              onFailure={::this.errorGoogle}
              onRequest={::this.onRequest}
              uxMode='redirect'
              redirectUri={window.location.origin + '/auth/google/callback'}
            />

它不调用onSuccess函数并重定向到“/auth/google/callback”。我无法从location.hash中获取此参数(但它有id_token)。我可以从哪里获取access_token?这可能吗?

oalqel3c

oalqel3c1#

我在服务器端(节点js)使用这段代码来动态处理具有ID令牌的情况和具有ACCESS令牌的情况。

const { OAuth2Client } = require('google-auth-library');
const unirest = require('unirest');

exports.user_google_login = async function (req, res) {
        const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID);
  
        const isValidIdToken = !!req.body.credential;
        //credentail refers to ID TOKEN
        
        const ticket = isValidIdToken
                     ? await client.verifyIdToken({
                       idToken: req.body.credential,
                       audience: process.env.GOOGLE_CLIENT_ID,
                    })
                     : await unirest
                      .get('https://www.googleapis.com/oauth2/v3/userinfo')
                      .headers({ Authorization: `Bearer ${req.body.access_token}` })
                      .send();

        const payload = isValidIdToken ? ticket.getPayload() : ticket.body;
        //payload will hold user details
    }

相关问题