Search code examples
reactjsspring-bootgoogle-oauth

Getting redirect_uri_mismatch with Sign on With Google


I'm getting redirect_uri_mismatch when the backend is attempting to exchange an authorization code for an ID token with Google.

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

NOTE: The JavaScript front end gets the authorization code just fine.

I've spent multiple days searching the web, Google's documentation, searching StackOverflow, chatting with ChatGPT. I'm stumped.

React front end using "@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>
);

Backend is Spring Boot 3.2.2 with Java 21, 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
Google Console:
GCP Console


Solution

  • Trying to follow the documentation for obtaining an authorization code and exchanging it for an ID token (JWT) in the backend: https://developers.google.com/identity/sign-in/web/server-side-flow

    Discovered an undocumented value for redirectUri. The value for redirectUri in the backend must be postmessage. Found it here: https://github.com/MomenSherif/react-oauth/issues/12

    When publishing an API always document magical values.