使用 GitLab 私有令牌调用 GitLab 端点时出现未经授权的错误

Unauthorized error when using GitLab Private Token to call GitLab endpoint

我正在尝试通过 HttpClient 访问 GitLab API 端点。首先,我使用

生成私有访问令牌
https://gitlab.example.com/oauth/token

然后使用此访问令牌,我尝试访问具有以下端点的标签或项目

https://gitlab.example.com/api/v4/projects/1/repository/tags/

https://gitlab.example.com/api/v4/projects/

在不使用访问令牌的情况下,我可以获得 public 信息,但是当使用令牌时,它会给出 401 未经授权的错误。我什至在 url 中尝试了私有令牌,它也给出了同样的错误。

https://gitlab.example.com/api/v4/projects/1/repository/tags?private_token=xxxxxxxxxxxxxxxxxxxxxxx

我的代码如下

private async Task<HttpResponseMessage> GetHttpResponse(string url)
{
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
                                                | SecurityProtocolType.Tls
                                                | SecurityProtocolType.Tls11
                                                | SecurityProtocolType.Tls12;

    var request = new HttpRequestMessage(HttpMethod.Get, url);
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeJson));
    request.Headers.Add("Private-Token", accessToken);

    return await Client.SendAsync(request).ConfigureAwait(false);
}

我不知道出了什么问题以及如何解决

您必须将 oauth headers 发送到

curl --header "Authorization: Bearer <your_access_token>" https://gitlab.example.com/api/v4/projects

试一试

像这样使用会给你组和子组项目的项目

curl --silent --header "Private-Token: YOUR_GITLAB_TOKEN" https://gitlab.example.com/api/v4/groups/<group_ID>/projects?include_subgroups=true

或者如果您只想要来自特定组的项目

curl --silent --header "Private-Token: YOUR_GITLAB_TOKEN" https://gitlab.example.com/api/v4/groups/<group_ID>/projects?per_page=100