gpt4 book ai didi

java - Firebase 推送 - 身份验证凭据无效

转载 作者:行者123 更新时间:2023-11-30 10:21:09 25 4
gpt4 key购买 nike

我在基于 Spring 的应用程序服务器中使用 Firebase Cloud Messaging REST API 向我的应用程序客户端发送推送消息。

从我的 IDE 运行时,一切正常。问题是从打包的 JAR 文件运行并尝试发送推送消息时,我得到:“身份验证凭据无效”和状态代码 401。

我的service-account.json文件在resources文件夹下,添加到类路径中:

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 相同的文件夹中。这导致了同样的错误。

我真的不确定为什么会这样,感谢任何帮助或猜测。

最佳答案

最终我通过从应用程序外部接收到 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");
}
}

关于java - Firebase 推送 - 身份验证凭据无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47964534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com