javaiosoauth-2.0google-oauthgoogle-oauth-java-client

Redirect_uri when trying to exchange an authcode from backend server when the authcode was received in an ios app


I have an ios app and a web app that gets authorization from users and generates an authcode and sends it to the backend java servlet which tries to exchange the authcode for access & refresh tokens. Exchanging the authcode from the web app is working but for authcodes generated from the ios app i'm getting the following error during the exchange.

com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request { "error" : "invalid_request", "error_description" : "Missing parameter: redirect_uri" }

This is the code that is doing the exchange

      public OAuthCodeExchangeResponse exchangeAuthCode(String authCode, boolean isIosApp) throws JSONException, IOException {
OAuthCodeExchangeResponse response = new OAuthCodeExchangeResponse();
GoogleClientSecrets clientSecrets = getClientSecrets(isIosApp);
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow =
    new GoogleAuthorizationCodeFlow.Builder(
        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
        .setAccessType("offline")
        .build();
GoogleTokenResponse tokenResponse = null;
if(isIosApp == false) {
  tokenResponse = flow.newTokenRequest(authCode)
      .setRedirectUri("postmessage")
      .execute();
} else {
  tokenResponse = flow.newTokenRequest(authCode).execute();
}
GoogleIdToken idToken = tokenResponse.parseIdToken();
GoogleIdToken.Payload payload = idToken.getPayload();
response.setAccessToken(tokenResponse.getAccessToken());
response.setEmail(payload.getEmail());
response.setIdToken(tokenResponse.getIdToken());
response.setRefreshToken(tokenResponse.getRefreshToken());
return response;
}

public GoogleClientSecrets getClientSecrets(boolean isIosApp) throws JSONException, IOException {
GoogleClientSecrets.Details d = new GoogleClientSecrets.Details();
if(isIosApp == false) {
  d.setClientId(WebClientId);
  d.setClientSecret(WebClientSecret);
} else {
  d.setClientId(PhoneClientId);
}
GoogleClientSecrets clientSecrets = new GoogleClientSecrets();
clientSecrets.setInstalled(d);
return clientSecrets;
}

What redirect_uri do i have to set when exchanging the authcode generated from the ios app? The credentials created for the ios app in the google developers console doesn't have a redirect uri set btw.


Solution

  • urn:ietf:wg:oauth:2.0:oob

    You need the flow for installed applications, see https://developers.google.com/identity/protocols/OAuth2InstalledApp#formingtheurl