I am facing this error when trying get the access token for OAuth 2.0 to send a notification to another phone.
The error:
com.google.auth.oauth2.GoogleAuthException: Error getting access token for service account: 400 Bad Request POST https://oauth2.googleapis.com/token {"error":"invalid_scope","error_description":"Invalid OAuth scope or ID token audience provided."}
From the documentation: https://developers.google.com/identity/protocols/oauth2/scopes, the scopes to request are correct.
This is the AccessToken class:
public class AccessToken {
private static final String firebaseMessagingScope1 = "https://www.googleapis.com/auth/firebase.messaging";
private static final String firebaseMessagingScope2 = "https://www.googleapis.com/auth/cloud-platform";
public String getAccessToken() {
try {
String jsonString = "{\n" +
" \"type\": \"service_account\",\n" +
" \"project_id\": \"....\",\n" +
" \"private_key_id\": \".....\",\n" +
" \"private_key\": \".......\\n\",\n" +
" \"client_email\": \"............\",\n" +
" \"client_id\": \"..........\",\n" +
" \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",\n" +
" \"token_uri\": \"https://oauth2.googleapis.com/token\",\n" +
" \"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\",\n" +
" \"client_x509_cert_url\": \"https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-u71wo%40........iam.gserviceaccount.com\",\n" +
" \"universe_domain\": \"googleapis.com\"\n" +
"}\n";
InputStream inputStream = new ByteArrayInputStream(jsonString.getBytes(StandardCharsets.UTF_8));
GoogleCredentials googleCredentials = GoogleCredentials.fromStream(inputStream);
googleCredentials.createScoped(Lists.newArrayList(firebaseMessagingScope1, firebaseMessagingScope2));
googleCredentials.refresh();
return googleCredentials.getAccessToken().getTokenValue();
} catch (IOException e) {
Log.e("error", e.toString());
return null;
}
}
}
Can anyone help me with this issue? any help/suggestion is very appreciated.
You're creating the GoogleCredentials
correctly, but you’re not actually assigning the scoped credentials.
You’re calling:
googleCredentials.createScoped(...);
But you're not using the result of createScoped(...)
. This method returns a new instance with the scopes applied — it doesn't mutate the original object.
Update your code to assign the result of createScoped(...)
to googleCredentials
:
GoogleCredentials googleCredentials = GoogleCredentials.fromStream(inputStream)
.createScoped(Lists.newArrayList(firebaseMessagingScope1, firebaseMessagingScope2));