我在基于Spring的应用服务器中使用Firebase Cloud Messaging REST API向我的应用客户端发送推送消息。
从我的IDE运行时,一切都很完美。 问题是当从打包的JAR文件运行并尝试发送推送消息时,我得到:“身份验证凭据无效”和状态代码401.
我的service-account.json文件位于资源文件夹下,该文件夹已添加到类路径中:
我通过以下方式访问它:
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();
}
我还尝试了不同的方法来访问service-account.json,例如将它放在项目根目录中并像这样检索它:
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();
}
当从打包的JAR运行时,我在JAR外部提供了service-account.json文件,与JAR位于同一文件夹中。 这导致了同样的错误。
我真的不确定为什么会这样,任何帮助或猜测都会受到赞赏。
答案 0 :(得分:1)
最终我通过从应用程序外部接收service-account.json的完整路径来解决它:
@Value("${service.account.path}")
private String serviceAccountPath;
在application.properties中:
service.account.path = /path/to/service-account.json
代码:
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");
}
}