Python request basic authentication

Python request basic authentication

Basic Auth is one of the many HTTP authorization technique used to validate access to a HTTP endpoint. Understanding Basic Auth is very simple, the user requesting the access to an endpoint has to provide either,

  • Username and password as credentials in the API call (or)
  • Basic authorization token as credentials in the request header

Let us explore both the ways in python. For the purpose of demo, we will be using basic auth end point exposed by postman

https://postman-echo.com/basic-auth

Although this is a GET request, Basic Auth calls for all the other HTTP methods will remain the same with an exception that instead of get() method, use corrosponding method exposed by requests library.

1. USERNAME & PASSWORD AS CREDENTIALS:

We can directly embed basic auth username and password in the request by passing username and password as a tuple to the auth param and the get() method in requests will take care of the basic authorization for us.

import requests url = "https://postman-echo.com/basic-auth" username = "postman" password = "password" response = requests.get(url, auth=(username, password)) print(response.status_code) print(response.json())

2. BASIC AUTH TOKEN AS CREDENTIALS:

There is a chance that for an API, you receive only the basic auth token instead of username and password. In this scenario, all you need to do is to embed the basic auth token as Authorization header while making the API call. A sample basic auth token would look like this

Basic cG9zdG1hbjpwYXNzd29yZA==
import requests url = "https://postman-echo.com/basic-auth" header = response = requests.get(url, headers=header) print(response.status_code) print(response.json())

OUTPUT

For requests made with valid Basic Auth credentials

Читайте также:  Javascript iframe border style

For requests made with invalid Basic Auth credentials

Источник

Authentication¶

https://farm5.staticflickr.com/4258/35550409215_3b08d49d22_k_d.jpg

This document discusses using various kinds of authentication with Requests.

Many web services require authentication, and there are many different types. Below, we outline various forms of authentication available in Requests, from the simple to the complex.

Basic Authentication¶

Many web services that require authentication accept HTTP Basic Auth. This is the simplest kind, and Requests supports it straight out of the box.

Making requests with HTTP Basic Auth is very simple:

>>> from requests.auth import HTTPBasicAuth >>> requests.get(‘https://api.github.com/user’, auth=HTTPBasicAuth(‘user’, ‘pass’))

In fact, HTTP Basic Auth is so common that Requests provides a handy shorthand for using it:

>>> requests.get(‘https://api.github.com/user’, auth=(‘user’, ‘pass’))

Providing the credentials in a tuple like this is exactly the same as the HTTPBasicAuth example above.

netrc Authentication¶

If no authentication method is given with the auth argument, Requests will attempt to get the authentication credentials for the URL’s hostname from the user’s netrc file. The netrc file overrides raw HTTP authentication headers set with headers= .

If credentials for the hostname are found, the request is sent with HTTP Basic Auth.

Digest Authentication¶

Another very popular form of HTTP Authentication is Digest Authentication, and Requests supports this out of the box as well:

>>> from requests.auth import HTTPDigestAuth >>> url = ‘https://httpbin.org/digest-auth/auth/user/pass’ >>> requests.get(url, auth=HTTPDigestAuth(‘user’, ‘pass’))

OAuth 1 Authentication¶

A common form of authentication for several web APIs is OAuth. The requests-oauthlib library allows Requests users to easily make OAuth 1 authenticated requests:

>>> import requests >>> from requests_oauthlib import OAuth1 >>> url = ‘https://api.twitter.com/1.1/account/verify_credentials.json’ >>> auth = OAuth1(‘YOUR_APP_KEY’, ‘YOUR_APP_SECRET’, . ‘USER_OAUTH_TOKEN’, ‘USER_OAUTH_TOKEN_SECRET’) >>> requests.get(url, auth=auth)

For more information on how to OAuth flow works, please see the official OAuth website. For examples and documentation on requests-oauthlib, please see the requests_oauthlib repository on GitHub

OAuth 2 and OpenID Connect Authentication¶

The requests-oauthlib library also handles OAuth 2, the authentication mechanism underpinning OpenID Connect. See the requests-oauthlib OAuth2 documentation for details of the various OAuth 2 credential management flows:

Other Authentication¶

Requests is designed to allow other forms of authentication to be easily and quickly plugged in. Members of the open-source community frequently write authentication handlers for more complicated or less commonly-used forms of authentication. Some of the best have been brought together under the Requests organization, including:

If you want to use any of these forms of authentication, go straight to their GitHub page and follow the instructions.

New Forms of Authentication¶

If you can’t find a good implementation of the form of authentication you want, you can implement it yourself. Requests makes it easy to add your own forms of authentication.

To do so, subclass AuthBase and implement the __call__() method:

>>> import requests >>> class MyAuth(requests.auth.AuthBase): . def __call__(self, r): . # Implement my authentication . return r . >>> url = ‘https://httpbin.org/get’ >>> requests.get(url, auth=MyAuth())

When an authentication handler is attached to a request, it is called during request setup. The __call__ method must therefore do whatever is required to make the authentication work. Some forms of authentication will additionally add hooks to provide further functionality.

Further examples can be found under the Requests organization and in the auth.py file.

Requests is an elegant and simple HTTP library for Python, built for human beings. You are currently looking at the documentation of the development release.

Stay Informed

Receive updates on new releases and upcoming projects.

Other Projects

  • Open DSM-5M
  • Requests-HTML
  • howtopython.org
  • pipenv
  • pep8.org
  • httpbin.org
  • The Python Guide
  • Maya: Datetimes for Humans
  • Records: SQL for Humans
  • Legit: Git for Humans
  • Tablib: Tabular Datasets

Translations

Table of Contents

Источник

Оцените статью