Richardweber32
Richardweber32

Reputation: 168

Using a personal access token for azure devops API repository manipulation

I have generated a personal access token from the Azure Devops user interface but am unable to use this to make requests against the Devops API.

I have tried many different header fields, but I am always redirected to the log in page as though I hadn't authenticated.

token = #Token generated on Devops project page
token_bytes = token.encode('utf-8')
token64 = base64.b64encode(token_bytes)
authorization_string = "basic " + str(token64)

repo_endpoint_url = "https://dev.azure.com/{organization}/{project}/_apis/git/repositories?api-version=5.1".format(organization=organization, project=project)

headers = {"Content-Type" : "application/json", "Authorization" : authorization_string}

response = requests.get(repo_endpoint_url, headers)

response is always 203 with login page HTML. This is what I'd expect to see if I didn't have an access token in the header.

I have tried, "Bearer" instead of "basic", I have tried adding {username}:{token}, and many other little tweaks.

What am I doing wrong?

Upvotes: 1

Views: 3378

Answers (3)

Peter Trcka
Peter Trcka

Reputation: 1521

I had the same issue. This seems to me that if you create a PAT without a Code scope, and you want to add a Code scope you must regenerate PAT.

Same vice versa: If you want to add a Wiki scope to PAT with only a Code scope (for example you want to extend PAT which you have created in the REPOS section during the repository clone process) you must regenerate the PAT.

Upvotes: 0

user15206036
user15206036

Reputation: 11

After almost 1 week of investigating recreation of TOKEN was the only thing that helped me!

Upvotes: 0

DSpirit
DSpirit

Reputation: 2280

I just scrapbooked following code which worked for me:

import requests
import base64

repo_endpoint_url = "https://dev.azure.com/<organization>/<project>/_apis/git/repositories?api-version=5.1"

username = "" # This can be an arbitrary value or you can just let it empty
password = "<your-password-here>"
userpass = username + ":" + password
b64 = base64.b64encode(userpass.encode()).decode()
headers = {"Authorization" : "Basic %s" % b64} 

response = requests.get(repo_endpoint_url, headers=headers)
print(response.status_code) # Expect 200

Upvotes: 9

Related Questions