go - 获取 gitlab repo 列表 : says "401 Unauthorized"

标签 go oauth gitlab

我正在尝试使用 OAuth token 从 gitlab 获取 repo 列表。

我的代码看起来像这样......(“github.com/xanzy/go-gitlab”)

    repositories := []string{}
    client, _ := gitlab.NewClient(gitRepoRequest.Token, gitlab.WithBaseURL("https://gitlab.com/api/v4"))
    fmt.Println("client...", client.ContainerRegistry)

    projects, _, projectListErr := client.Projects.ListProjects(&gitlab.ListProjectsOptions{})
    for _, project := range projects {
        fmt.Println("ID===", project.ID)
        fmt.Println("NAME===", project.Name)
    }

    if projectListErr != nil {
        // return err
    }

我无法获取项目列表..“projectListErr”说... GET https://gitlab.com/api/v4/projects: 401 {消息:401 未经授权}

我对代币值(value)充满信心,因为我正在使用相同的代币获取 repo 的所有分支列表,该代码看起来像......(“github.com/go-git/go-git/v5”)

rem := git.NewRemote(gitMemory.NewStorage(), &gitConfig.RemoteConfig{
    Name: "origin",
    URLs: []string{gitBranchesRequest.Repository},
})

refs, listErr := rem.List(&git.ListOptions{
    Auth: &gitHttp.BasicAuth{Username: gitUserName, Password: gitBranchesRequest.Token},
})

这是否意味着我使用的库有问题? github.com/xanzy/go-gitlab

最佳答案

这取决于 type of token you are using .

例如,project access token很可能会让您访问存储库(针对该项目)的所有分支列表。

但是对于使用/projects API,401意味着身份验证信息无效或丢失。

所以一定要使用 PAT (Personal Access Token) ,链接到用户,而不是项目。


OP Keval Bhogayata添加 the comments :

I have found the issue.

The library I am using ("xanzy/go-gitlab"), has different client creation functions for different tokens.

I have been using the function that supports personal access token. Instead I was supposed to use "NewOAuthClient" !

// NewOAuthClient returns a new GitLab API client. To use API methods which
// require authentication, provide a valid oauth token.
func NewOAuthClient(token string, options ...ClientOptionFunc) (*Client, error)

关于go - 获取 gitlab repo 列表 : says "401 Unauthorized",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70532432/

相关文章:

c# - 如何使用 OAuth 像小部件一样保护客户端脚本?

windows - 配置 git 以支持使用不同操作系统的程序员

go - 基于异步回调的 API 的同步 API 包装器

go - 一次添加两个项目以在 for 循环中构造

api - LinkedIn 的访问 token 更新流程可以在服务器上执行吗?

git - 当提交包含某些关键字时,如何配置 git 存储库以警告/拒绝

jenkins - 如何在 gitlab 中为多分支管道 jenkins 添加 webhook

excel - 将 Excel 十进制日期时间转换为 time.Time

go - 在golang中嵌入具有相同属性名称的模型结构

actionscript-3 - OAuth 和 Flickr 问题 - 无法请求 token