Merge Request API in GitLab CI/CD returning unauthorized error

i found the answer: How to get Gitlab merge request description in Gitlab CI?

But there is no answer to the request:

$CI_API_V4_URL/projects/$CI_PROJECT_ID/merge_requests/$CI_MERGE_REQUEST_IID

i added a header:

PRIVATE-TOKEN: $TOKEN

Where $TOKEN - CI_BUILD_TOKEN or CI_JOB_TOKEN, but answer:

HTTPCode: 401

UPD. I created script:

#!/usr/bin.env bash
# -*- coding: utf-8 -*- 

urlBase="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/merge_requests/${CI_MERGE_REQUEST_IID}
echo "[--] urlBase: ${urlBase}"
echo "[--] key + build"
curl "${urlBase}?private_token=${CI_BUILD_TOKEN}"
echo "[--] key + job"
curl "${urlBase}?private_token=${CI_JOB_TOKEN}"
echo "[--] header + build"
curl --header "PRIVATE-TOKEN: ${CI_BUILD_TOKEN}" "${urlBase}"
echo "[--] header + job"
curl --header "PRIVATE-TOKEN: ${CI_JOB_TOKEN}" "${urlBase}"
echo "[--] header2 + build"
curl --header "Authorization: Bearer ${CI_BUILD_TOKEN}" "${urlBase}"
echo "[--] header2 + job"
curl --header "Authorization: Bearer ${CI_JOB_TOKEN}" "${urlBase}"

but output:

{"message":"401 Unauthorized"}

Upvotes: 2

Views: 4875

Answers (1)

DV82XL
DV82XL

Reputation: 6639

Assuming you're calling the GitLab API using cURL, you need to pass the API token explicitly. Read the GitLab Documentation carefully, since there are quite a few gotchas.

Credentials in cURL Command

Here are some common ways for passing credentials in a cURL command:

As a parameter:

curl "$CI_API_V4_URL/projects/$CI_PROJECT_ID/merge_requests/$CI_MERGE_REQUEST_IID?private_token=<your_access_token>"

As a header:

curl --header "PRIVATE-TOKEN: <your_access_token>" "$CI_API_V4_URL/projects/$CI_PROJECT_ID/merge_requests/$CI_MERGE_REQUEST_IID"

CI Job Token

The GitLab documentation specifies which API calls can be made with $CI_JOB_TOKEN:

With a few API endpoints you can use a GitLab CI/CD job token to authenticate with the API: Packages, Artifacts, Pipeline Triggers, Release Creation, Terraform Plan.

Note that Merge Request is not in that list, so that won't work.

CI Build Token

According to this issue, $CI_BUILD_TOKEN was deprecated in GitLab 9.x and was renamed to $CI_JOB_TOKEN, so that won't work either.

Personal Access Token

You can authenticate to a GitLab API using Personal Access Tokens, or PATs. First, create your PAT using these instructions. Make sure you select api as the scope. Then, add the token to a GitLab variable following these instructions. Make sure you enable "Mask Variable" so that your token is not exposed in logs. Now, in gitlab-ci.yml, the variable you created will be available as an environment variable.

Upvotes: 7

Related Questions