Search code examples
gitlabdotnet-httpclientunauthorized

Unauthorized error when using GitLab Private Token to call GitLab endpoint


I am trying to reach GitLab API endpoint via HttpClient. Firstly, I am generating private access token with

https://gitlab.example.com/oauth/token

then with this access token I'm trying to reach tags or projects with endpoints below

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

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

Without using access token I can reach public information, but when using the token it gives 401 Unauthorized error. I even tried private token inside url, it gives same error too.

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

My code is below

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);
}

I do not know what is wrong and how to fix it


Solution

  • You have to send the oauth headers too

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

    try it