Android应用使用Token调用GitHub API时认证失败问题排查
问题分析与解决方案
核心问题排查
你遇到的Requires authentication错误,大概率是以下几个原因导致:
1. Authorization请求头格式错误
GitHub API要求认证头格式为 Bearer <你的访问令牌>,如果你的代码中仅传递了令牌字符串(比如ghp_xxxxxx)而没有添加Bearer 前缀,接口会判定未授权。
修复方式:
调用接口时,将令牌拼接成完整格式:
val authHeader = "Bearer ${yourAccessToken}" apiService.getGithubRepositories(authHeader)
2. 接口路径错误(与需求不匹配)
你要获取的是仓库列表,但当前代码中使用的@GET("user")是获取授权用户基本信息的接口,获取仓库列表的正确接口路径是/user/repos。
修复方式:
修改ApiService中的对应方法:
@Headers( "Accept: application/vnd.github+json", "X-GitHub-Api-Version: 2022-11-28" ) @GET("user/repos") // 建议定义数据类接收响应,替代ResponseBody suspend fun getGithubRepositories(@Header("Authorization") authHeader: String): Response<List<RepoResponse>> // 示例RepoResponse数据类 data class RepoResponse( val id: Long, val name: String, val full_name: String, // 按需添加其他字段 )
3. 访问令牌权限不足
确保你在GitHub生成的Personal Access Token(PAT)拥有对应权限:
- 若需访问私有仓库,勾选
repo权限 - 仅访问公有仓库,勾选
public_repo权限
4. 验证请求头是否正确发送
添加OkHttp日志拦截器,查看实际发送的请求头,确认Authorization是否正确传递:
// 在AppModule的provideRetrofit方法中添加 val loggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.HEADERS } val okHttpClient = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build() return Retrofit.Builder() .baseUrl(BASE_URL) .client(okHttpClient) // 添加客户端 .addConverterFactory(Json.asConverterFactory(contentType)) .build()
之后在Logcat中查看请求头,确认Authorization字段是否为正确的Bearer xxxx格式。
内容的提问来源于stack exchange,提问作者Влад Михнёнок
相关产品推荐
相关产品推荐

