Peter Boomsma
Peter Boomsma

Reputation: 9846

Azure DevOps REST API returns a 403 when using the system OAuth token during a build

I'm running a script:

# Variables
$organization = "****"
$project = "****"
$repositoryId = "****"
$pullRequestId = $env:BUILD_PULLREQUEST_ID

$pat = "Bearer $env:System_AccessToken"
$featureReleaseUrl = "http://" + $env:prSourceBranchName + ".azurewebsites.net"

$body = @"
    {
        "comments": [
            {
                "content": "Link naar feature release $featureReleaseUrl"
            }
        ]
    }
"@ 

$createThreadInPRUrl = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repositoryId/pullRequests/$pullRequestId/threads?api-version=5.0"
if ($pullRequestId) {
    Invoke-RestMethod -Uri $createThreadInPRUrl -Headers @{Authorization = $pat} -Body $body -Method Post -ContentType 'application/json'
}

When it runs it returns a:

##[error]The remote server returned an error: (403) Forbidden.

I've created a Personal Access Tokens in my personal settings.

I've also created this script:

# Variables
$organization = "****"
$project = "****"
$buildId = $****

$pat = "Bearer $env:System_AccessToken"

if (!$env:Build_PullRequest_SourceBranchName) {
    $retrieveSourceBranchFromBuildURL = "https://dev.azure.com/$organization/$project/_apis/build/builds/$buildId" + "?api-version=5.0"
    $buildInformation = Invoke-RestMethod -Uri $retrieveSourceBranchFromBuildURL -Headers @{Authorization = $pat } -Method Get -ContentType 'application/json'
    $SourceBranchFromBuild = $buildInformation.sourceBranch.split('/')[-1]

    Write-Host "### no Build PullRequest SourceBranchName available ###"
    Write-Host "##vso[task.setvariable variable=prSourceBranchName;]"$SourceBranchFromBuild


}

And this runs fine. The difference between the first and second script is that the first is a POST and the second a GET. But they both use the $pat token.

Upvotes: 1

Views: 2524

Answers (1)

Mengdi Liang
Mengdi Liang

Reputation: 19026

Even though the token you used is System.AccessToken, if you don't have access permission of Pull Request, you will also could not operate it.

Go Project Setting--> Repositories--> Repository you want to access, locate your account or the group you are in. Check the permission state of Contribute to pull requests.

You must have this Contribute to pull requests permission allowed, so that you can add the comment to PR.

enter image description here

Upvotes: 3

Related Questions