Reputation: 857
I am using Firebase Cloud Messaging REST API in my Spring based application server to send push messages to my app clients.
When running from my IDE, everything works perfectly. The problem is when running from packaged JAR file and trying to send the push message, I get: "Authentication credentials invalid" and status code 401.
My service-account.json file is under resources folder, which is added to the classpath:
I am accessing it in the following way:
private String getAccessToken() throws IOException {
Resource resource = new ClassPathResource("service-account.json");
GoogleCredential googleCredential = GoogleCredential
.fromStream(resource.getInputStream())
.createScoped(Collections.singletonList("https://www.googleapis.com/auth/firebase.messaging"));
googleCredential.refreshToken();
return googleCredential.getAccessToken();
}
I have also tried different ways of accessing the service-account.json, such as placing it in the project root and retrieving it like this:
private String getAccessToken() throws IOException {
File file = new File("service-account.json");
GoogleCredential googleCredential = GoogleCredential
.fromStream(new FileInputStream(file))
.createScoped(Collections.singletonList("https://www.googleapis.com/auth/firebase.messaging"));
googleCredential.refreshToken();
return googleCredential.getAccessToken();
}
And when running from packaged JAR I supplied the service-account.json file outside the JAR, in the same folder as the JAR. This resulted in the same error.
I'm really not sure why this is happening, any help or speculation is appreciated.
Upvotes: 2
Views: 783
Reputation: 857
Eventually I solved it by receiving a full path to the service-account.json from outside the app:
@Value("${service.account.path}")
private String serviceAccountPath;
In application.properties:
service.account.path = /path/to/service-account.json
And the code:
private String getAccessToken() throws IOException {
GoogleCredential googleCredential = GoogleCredential
.fromStream(getServiceAccountInputStream())
.createScoped(Collections.singletonList("https://www.googleapis.com/auth/firebase.messaging"));
googleCredential.refreshToken();
return googleCredential.getAccessToken();
}
private InputStream getServiceAccountInputStream() {
File file = new File(serviceAccountPath);
try {
return new FileInputStream(file);
} catch (FileNotFoundException e) {
throw new RuntimeException("Couldn't find service-account.json");
}
}
Upvotes: 1