I am trying to get repo list from gitlab using OAuth token.
My code looks something like this ... ("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
}
I am not able to get the project list.. the "projectListErr" says ...
GET https://gitlab.com/api/v4/projects: 401 {message: 401 Unauthorized}
I am confident about the token value because I am getting list of all branches for a repo using the same token, that code looks like ... ("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},
})
Does that mean there is an issue with the library that I am using ? github.com/xanzy/go-gitlab
CodePudding user response:
It depends on the type of token you are using.
For instance, a project access token might very well give you access to the list of all branches for a repository (for that project).
But for using the /projects
API, 401 means the authentication information is not valid or is missing.
So make sure to use a PAT (Personal Access Token), linked to a user, not a project.
The OP Keval Bhogayata adds in 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)