You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

获取OAuth 2.0 AccessToken时遭遇invalid_scope错误求助

问题排查与解决方案

核心问题

你代码中的googleCredentials.createScoped()调用存在错误:该方法会返回一个新的GoogleCredentials实例,而非修改原对象。当前代码仅调用方法但未接收返回值,导致实际刷新token的仍是未设置scope的原始凭证,因此触发invalid_scope错误。

修正后的代码

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);

            // 关键修正:接收createScoped返回的新实例
            googleCredentials = googleCredentials.createScoped(Lists.newArrayList(firebaseMessagingScope1, firebaseMessagingScope2));

            googleCredentials.refresh();

            return googleCredentials.getAccessToken().getTokenValue();

        } catch (IOException e) {
            Log.e("error", e.toString());
            return null;
        }
    }
}

额外排查建议

  • 确认服务账号已分配Firebase Cloud Messaging Admin角色,无权限也可能导致类似报错
  • 检查scope字符串是否完全正确,避免多余空格、拼写错误或转义问题
  • 建议通过文件路径加载服务账号JSON(而非硬编码),减少private_key等字段的转义错误风险

内容的提问来源于stack exchange,提问作者carl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 03:22:43