1
votes

How can I authenticate to Azure DevOps REST API in a python script? I found that there are 2 methods :

  • Using personal access token (PAT)
  • Using OAuth 2.0

I am using the second method. Followed the steps in this documentation: https://docs.microsoft.com/en-us/azure/devops/integrate/get-started/authentication/oauth?view=azure-devops

I wrote this function to autherize to azure DevOps using OAuth 2.0:

def get_authenticated():

    client_id = < my client ID as a string >
    state = "user1"
    scope = "vso.graph_manage%20vso.identity_manage%20vso.profile_write%20vso.project_manage%20vso.tokenadministration%20vso.tokens"
    callback_URL = < Callback URL to my azure devops account >

    # Azure DevOps Services authorization endpoint
    Auth_URL = "https://app.vssps.visualstudio.com/oauth2/authorize?client_id=" + client_id + "&response_type=Assertion&state=" + state + "&scope=" + scope + "&redirect_uri=" + callback_URL
    headers = {'Accept': 'application/json;api-version=1.0'}

    print(Auth_URL)

    response = requests.get(Auth_URL,headers = headers)
    print(response)
    print(response.status_code)
    print(response.headers['content-type'])

    response.raise_for_status() 

But when calling this function, output I am getting is:

<Response [203]>
203
text/html; charset=utf-8

The auth URL is correct because when I tried to access the same URL in a browser it successfully redirects to a form to enter azure user credentials.

The expected behavior of the script is, when the auth_url is requested, Azure DevOps Services should ask the user to authorize. I think that should be done by prompting for username&password in terminal/via a browser.

I am totally new to python scripting and REST APIs. Can someone help me by pointing out the faults in my code or pointing to some samples?

1

1 Answers

0
votes

The http error 203 indicates that the returned metainformation is not a definitive set of the object from a server with a copy of the object, but is from a private overlaid web. In your code,you added headers = {'Accept': 'application/json;api-version=1.0'}, but in fact the content type should be application/x-www-form-urlencoded.

You can use some OAuth2 library for python to authenticate to Azure DevOps REST API, such as OAuthLib. It includes sevelral samples.

Also, you can refer to following topic, hope it is helpful for you.

Tutorial for using requests_oauth2