使用Python调用GitLab服务器时遭遇HTTP Error 403 Forbidden问题
GitLab仓库存储用量获取403 Forbidden错误排查
我编写了一段Python代码用于获取GitLab仓库的存储用量,但运行时始终返回403 Forbidden error。目标仓库test_repo_1隶属于test_group_1组,我分别创建了项目级和组级(组访问令牌)的Maintainer角色令牌,单独在脚本中使用后均触发403错误。
Python代码
import gitlab GITLAB_URL = "https://gitlab.com" GL_GROUP_TOKEN = '<Group token & Project access token>' def grant_access(gl_project_id): gl = gitlab.Gitlab(GITLAB_URL, private_token = GL_GROUP_TOKEN) project = gl.projects.get(gl_project_id) storage = project.storage.get() print("storage::",storage) def main(): gl_project_id='8724648' role_requested='' grant_access(gl_project_id) main()
错误日志
python3 storage.py Traceback (most recent call last): File "/home/nairv/.local/lib/python3.7/site-packages/gitlab/exceptions.py", line 336, in wrapped_f return f(*args, **kwargs) File "/home/nairv/.local/lib/python3.7/site-packages/gitlab/mixins.py", line 154, in get server_data = self.gitlab.http_get(self.path, **kwargs) File "/home/nairv/.local/lib/python3.7/site-packages/gitlab/client.py", line 829, in http_get "get", path, query_data=query_data, streamed=streamed, **kwargs File "/home/nairv/.local/lib/python3.7/site-packages/gitlab/client.py", line 797, in http_request response_body=result.content, gitlab.exceptions.GitlabHttpError: 403: 403 Forbidden The above exception was the direct cause of the following exception: Traceback (most recent call last): File "storage.py", line 20, in <module> main() File "storage.py", line 18, in main grant_access(gl_project_id) File "storage.py", line 12, in grant_access storage = project.storage.get() File "/home/nairv/.local/lib/python3.7/site-packages/gitlab/v4/objects/projects.py", line 1257, in get return cast(ProjectStorage, super().get(**kwargs)) File "/home/nairv/.local/lib/python3.7/site-packages/gitlab/exceptions.py", line 338, in wrapped_f raise error(e.error_message, e.response_code, e.response_body) from e gitlab.exceptions.GitlabGetError: 403: 403 Forbidden
令牌权限配置
- 组访问令牌:已勾选
read_api、read_repository、write_repository、read_registry、write_registry权限,角色为Maintainer - 项目访问令牌:已勾选
read_api、read_repository、write_repository权限,角色为Maintainer
排查及解决方案
- 确认API权限要求:GitLab 15.0及以上版本中,访问项目存储用量API(
/projects/:id/storage)需要read_repository_storage权限,该权限默认仅管理员拥有,普通Maintainer角色不具备。 - 调整令牌权限:
- 若使用GitLab 15.0+,需由管理员为令牌添加
read_repository_storage权限,或直接使用拥有管理员权限的个人访问令牌进行测试。
- 若使用GitLab 15.0+,需由管理员为令牌添加
- 排除代码问题:用curl直接调用API验证权限,确认是否是代码逻辑问题:
若curl同样返回403,可确定是权限配置问题而非代码问题。curl --header "PRIVATE-TOKEN: <你的令牌>" "https://gitlab.com/api/v4/projects/8724648/storage" - 检查实例设置:如果是自托管GitLab,需确认管理员是否开启了该API的访问权限,部分实例可能会限制存储用量API的访问范围。
内容的提问来源于stack exchange,提问作者vinod827
相关产品推荐
相关产品推荐

