0

I am trying to access an API on azurewebsites.net though requests in python like this:

print(uncurl.parse(
"curl -X GET --header 'Accept: application/json' 'https://pmd-qa-api.azurewebsites.net/api/Portfolios'"))

r = requests.get("https://pmd-qa-api.azurewebsites.net/api/Portfolios",
                 headers={
                     "Accept": "application/json"},
                 auth=('myemail', 'mypass'))
print(r.status_code)
print(r.content)

but I get error 401: b'You do not have permission to view this directory or page. I am entering correct credentials instead of myemail and mypass. I can access the API through browser after logging in with the same credentials. Is the something I need to configure in Azure to make my API request authentication successful? TiA

sleepyPanda
  • 69
  • 1
  • 7

1 Answers1

1

To call the API as a user, using the device code flow

The device flow allows limited-input experiences (e.g. think a TV, or a seldom-used console app) to obtain an OAuth 2.0 access token in the context of a user, while allowing the user to perform the actual sign-in on a different device with better input capabilities (e.g. on a smartphone or desktop computer).

You will need to:

  • Register your client app in Azure AD as a native client app (this is important, as it tells Azure AD that this is a public client, which allows the app to get an access token with delegated permissions without the app authenticating (because public clients can't keep a secret from the user).
  • Declare that your client app requires access to your API (which would be registered as a separate web app/web API).

The device code flow consists of:

  • The client app makes a request to Azure AD to get an device code. This device code is displayed to the user (along with a URL).
  • On a separate device (or, e.g. in full-fledged browser in the same device), the user visits the given URL, and inputs the given device code. The user is prompted to sign in and is shows a success message when they do so.
  • Meanwhile, the client app periodically polls Azure AD to see if the user has redeemed the device code (and signed in). If yes, the client app received the access token.

With Python, it is again useful to use ADAL for Python. The request to get the device code would look like this:

context = adal.AuthenticationContext('https://login.microsoftonline.com/{tenant-id}')
code = context.acquire_user_code('https://api.example.com', '{client-id}')
print(code['message'])

Check out this SO question around the same: Azure AD Authentication Python Web API

Further, if you want to test it locally, you need to login and get access token and add it as an Authorization header in the request.

Harshita Singh
  • 4,590
  • 1
  • 10
  • 13