Firebase Distribution API OAuth2授权失败:401认证错误求助
解决Firebase Distribution API 401认证错误的方法
核心问题:AccessToken请求的Scope错误
你调用GetAccessTokenForRequestAsync时传入的是授权端点URL,而非Firebase Distribution API所需的权限范围(Scope),这会导致获取的Token没有访问该API的权限。
修正步骤:
替换正确的Scope
将获取Token的代码改为传入Firebase Distribution API专属Scope:var token = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync("https://www.googleapis.com/auth/firebase.distribution");该Scope是访问Firebase Distribution API必须的权限标识。
验证API请求URL的正确性
确认apps后的参数是你的应用包名/ID(比如com.yourcompany.yourapp),而非项目ID。正确的URL格式应为:https://firebaseappdistribution.googleapis.com/v1/projects/myApp/apps/com.yourcompany.yourapp/releases确认服务账户权限
确保你的服务账户已被授予Firebase App Distribution Admin或Firebase Admin角色:- 进入Google Cloud控制台的IAM页面
- 找到对应的服务账户,添加上述角色并保存
修正后的完整代码示例:
var credential = GoogleCredential.FromJsonParameters(new JsonCredentialParameters() { Type = "service_account", ProjectId = "myApp", PrivateKeyId = "************", PrivateKey = "-----BEGIN PRIVATE KEY-----key-----END PRIVATE KEY-----\n", ClientEmail = "firebase-adminsdk-fbsvc@*******.iam.gserviceaccount.com", ClientId = "**************", TokenUri = "https://oauth2.googleapis.com/token", UniverseDomain = "googleapis.com" }); // 使用正确的Scope获取Token var token = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync("https://www.googleapis.com/auth/firebase.distribution"); try { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); // 替换为正确的应用ID string url = "https://firebaseappdistribution.googleapis.com/v1/projects/myApp/apps/com.yourcompany.yourapp/releases"; HttpResponseMessage response = await client.GetAsync(url); string result = await response.Content.ReadAsStringAsync(); Console.WriteLine("Response: " + result); } } catch(Exception e) { Console.WriteLine("Error: " + e.Message); }
内容的提问来源于stack exchange,提问作者DOCZIC
相关产品推荐
相关产品推荐

