使用 Google 登录时获取重定向_uri_不匹配

问题描述 投票:0回答:1

当后端尝试与 Google 交换 ID 令牌的授权代码时,我收到了 redirect_uri_mismatch。

400 Bad Request
POST https://oauth2.googleapis.com/token
{
  "error": "redirect_uri_mismatch",
  "error_description": "Bad Request"
}

注意:JavaScript 前端获取授权码就可以了。

我花了很多天搜索网络、Google 文档、搜索 StackOverflow、与 ChatGPT 聊天。我被难住了。

使用“@react-oauth/google”反应前端:“^0.12.1”

const login = useGoogleLogin({
    flow: 'auth-code',
    onSuccess: async (response) => {
        try {
            var data = { code: response.code };
            const session = await post('api/v1/sessions', data);
        } catch (error) {
            console.log(error);
        }
    },
    onError: error => console.log(error),
    redirect_uri: 'http://localhost:5173/login'
});
return (
    <div className="p-4">
        <div className="space-y-6 text-left">
            <Button label="Sign with Google" onClick={() => login()} type="button" />
        </div>
    </div>
);

后端是带有 Java 21 的 Spring Boot 3.2.2,google-api-client-servlet 2.4.0

public GoogleIdToken getIdToken(ClientSecrets secrets, String authorizationCode) {
    try {
        var response = new GoogleAuthorizationCodeTokenRequest(
            new NetHttpTransport(),
            GsonFactory.getDefaultInstance(),
            secrets.getDetails().getTokenUri(),
            secrets.getDetails().getClientId(),
            secrets.getDetails().getClientSecret(),
            authorizationCode,
            "http://localhost:5173/login") // redirectUri
        .execute();
        return response.parseIdToken();
    } catch (Exception e) {
        throw e;
    }
}

redirectUri:http://localhost:5173/login
谷歌控制台:

reactjs spring-boot google-oauth
1个回答
0
投票

为了子孙后代,在这里回答。

尝试按照文档获取授权码并在后端将其交换为 ID 令牌 (JWT):https://developers.google.com/identity/sign-in/web/server-side-flow

解决方案是偶然发现一个未记录的redirectUri 值的实践。后端中的redirectUri的值必须是神奇的字符串“postmessage”。我在这里找到了它: https://github.com/MomenSherif/react-oauth/issues/12

亲爱的同事们,如果您要发布 API,请特别记录任何神奇的值。

© www.soinside.com 2019 - 2024. All rights reserved.