Gradle引入GitHub Packages依赖遇401未授权:如何配置凭据?
解决GitHub Packages拉取ThirtyInch依赖的401未授权问题
需要的凭据类型
必须使用GitHub个人访问令牌(Personal Access Token, PAT),GitHub已弃用账号密码直接访问Packages仓库的方式。令牌需勾选read:packages权限,这是读取GitHub Packages仓库的核心权限。
配置方法
方法1:项目级配置(单个项目生效)
修改项目根目录的settings.gradle(旧版Gradle可修改build.gradle),在仓库配置中加入凭据:
repositories { maven { url = uri("https://maven.pkg.github.com/GCX-HCI/ThirtyInch") credentials { username = "你的GitHub用户名" password = "你的GitHub个人访问令牌" } } }
安全优化:避免硬编码凭据
直接硬编码令牌存在泄露风险,建议用本地属性文件管理:
- 在项目根目录创建
local.properties文件,添加:
github.username=你的GitHub用户名 github.token=你的个人访问令牌
- 在
settings.gradle中读取该文件的配置:
def localProperties = new Properties() localProperties.load(new FileInputStream(rootProject.file("local.properties"))) repositories { maven { url = uri("https://maven.pkg.github.com/GCX-HCI/ThirtyInch") credentials { username = localProperties.getProperty("github.username") password = localProperties.getProperty("github.token") } } }
- 将
local.properties添加到项目的.gitignore文件中,防止提交到代码仓库。
方法2:系统级配置(所有本地项目生效)
在系统全局Gradle配置中设置凭据,无需每个项目单独配置:
- 找到用户目录下的
.gradle文件夹:- Windows:
C:\Users\<你的用户名>\.gradle - Mac/Linux:
~/.gradle
- Windows:
- 创建或修改
gradle.properties文件,添加:
githubPackagesUsername=你的GitHub用户名 githubPackagesToken=你的个人访问令牌
- 在项目的仓库配置中引用这些全局属性:
repositories { maven { url = uri("https://maven.pkg.github.com/GCX-HCI/ThirtyInch") credentials { username = project.findProperty("githubPackagesUsername") ?: System.getenv("GITHUB_PACKAGES_USERNAME") password = project.findProperty("githubPackagesToken") ?: System.getenv("GITHUB_PACKAGES_TOKEN") } } }
创建GitHub个人访问令牌的步骤
- 登录GitHub,进入「Settings」→「Developer settings」→「Personal access tokens」→「Tokens (classic)」
- 点击「Generate new token」,填写令牌描述,勾选
read:packages权限,设置有效期 - 生成令牌后立即复制保存,令牌仅会显示一次,丢失后需重新生成
内容的提问来源于stack exchange,提问作者lucky1928
相关产品推荐
相关产品推荐

