Google OAuth2 + React-google-login:尝试检索刷新令牌时出现“redirect_uri_mismatch”

jgt*_*res 2 javascript node.js google-oauth reactjs

你好吗?

我用来react-google-login在前端进行登录流程。

这是我的登录按钮设置:

<GoogleLogin
    accessType="offline"
    clientId={google.client_id}
    cookiePolicy="single_host_origin"
    onSuccess={handleLogin}
    onFailure={handleLoginFail}
    prompt="consent"
    responseType="code"
    scope="email profile https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/calendar.events.readonly openid"
    render={(_props) => (
        <Button className="google-login-btn" onClick={_props.onClick}>
            {props.buttonText} <GoogleIcon className="google-icon" height="20px" width="20px" />
        </Button>
    )}>
</GoogleLogin>
Run Code Online (Sandbox Code Playgroud)

这工作正常,我已成功收到authorization_code来自 Google 的邮件。问题是当我尝试为用户获取刷新令牌时。

这是我用来检索刷新令牌的代码:

const { client_id, client_secret, redirect_uri } = require('../config').google;

export async function GetRefreshToken(code) {
    try {
        const data = new URLSearchParams({
            code,
            client_id,
            client_secret,
            grant_type: 'authorization_code',
            redirect_uri
        });

        const headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        };

        const response = await axios.post('https://oauth2.googleapis.com/token', data, { headers });
        const parsedResponse = JSON.parse(response.data);

        if (parsedResponse.refresh_token) return parsedResponse;
        else return null;
    } catch (err) {
        console.error(err);
        throw err;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误:

{
  "error": "redirect_uri_mismatch",
  "error_description": "Bad Request"
}
Run Code Online (Sandbox Code Playgroud)

我的redirect_uri设置为http://localhost:3000/,并且我已经确认它在我的 Google 项目中配置正确。

我在这里缺少什么?

jgt*_*res 5

好吧,我终于找到了解决方法。

设置redirect_uriaspostmessage就可以了。

为什么?我仍然想知道......但它有效!

  • 同样的修复适用于“@react-oauth/google”生成的授权代码。 (2认同)