Hướng dẫn python requests authorization basic
I'm trying to use basic HTTP authentication in python. I am using the Requests library: Show
Response form auth variable:
But when I try to get data from different location, - I'm got 401 error
As far as I understand - in second request are not substituted session parameters. 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,
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
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 = {"Authorization" : "Basic cG9zdG1hbjpwYXNzd29yZA=="} response = requests.get(url, headers=header) print(response.status_code) print(response.json()) OUTPUTFor requests made with valid Basic Auth credentials 200 {'authenticated': True} For requests made with invalid Basic Auth credentials 401 {'authenticated': False} authentication.py
Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The permission and throttling policies can then use those credentials to determine if the request should be permitted. REST framework provides several authentication schemes out of the box, and also allows you to implement custom schemes. Authentication always runs at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed. The The Note: Don't forget that authentication by itself won't allow or disallow an incoming request, it simply identifies the credentials that the request was made with. For information on how to set up the permission policies for your API please see the permissions documentation. How authentication is determinedThe authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set If no class authenticates, The value of Setting the authentication schemeThe default authentication schemes may be set globally, using the
You can also
set the authentication scheme on a per-view or per-viewset basis, using the
Or, if you're using the
When an unauthenticated request is denied permission there are two different error codes that may be appropriate.
HTTP 401 responses must always include a The kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. The first authentication class set on the view is used when determining the type of response. Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a Apache mod_wsgi specific configurationNote that if deploying to Apache using mod_wsgi, the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level. If you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the
API ReferenceBasicAuthenticationThis authentication scheme uses HTTP Basic Authentication, signed against a user's username and password. Basic authentication is generally only appropriate for testing. If successfully authenticated,
Unauthenticated responses that are denied permission will result in an
Note: If you use TokenAuthenticationNote: The token authentication provided by Django REST framework is a fairly simple implementation. For an implementation which allows more than one token per user, has some tighter security implementation details, and supports token expiry, please see the Django REST Knox third party package. This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. To use the
Make sure to run The You'll also need to create tokens for your users.
For clients to authenticate, the token key should be included in the
If you want to use a different keyword in the header, such as If successfully authenticated,
Unauthenticated responses that are denied permission will result in an
The
Note: If you use Generating TokensBy using signalsIf you want every user to have an automatically generated Token, you can simply catch the User's
Note that you'll want to ensure you place this code snippet in an installed If you've already created some users, you can generate tokens for all existing users like this:
By exposing an api endpointWhen using
Note that the URL part of the pattern can be whatever you want to use. The
Note that the default By default, there are no permissions or throttling applied to the If you need a customized version of the For example, you may return additional user information beyond the
And in your
With Django adminIt is also possible to create Tokens manually through the admin interface. In case you are using a large user base, we recommend that you monkey patch the
Using Django manage.py commandSince version 3.6.4 it's possible to generate a user token using the following command:
this command will return the API token for the given user, creating it if it doesn't exist:
In case you want to regenerate the token (for example if it has been compromised or leaked) you can pass an additional parameter:
SessionAuthenticationThis authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website. If successfully authenticated,
Unauthenticated responses that are denied permission will result in an If you're using an AJAX-style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as Warning: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected. CSRF validation in REST framework works slightly differently from standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied. RemoteUserAuthenticationThis authentication scheme allows you to delegate authentication to your web server, which sets the To use it, you must have If successfully authenticated,
Consult your web server's documentation for information about configuring an authentication method, e.g.:
Custom authenticationTo implement a custom authentication scheme, subclass In some circumstances instead of returning Typically the approach you should take is:
You may also override the If the Note: When your custom authenticator is invoked by the request object's ExampleThe following example will authenticate any incoming request as the user given by the username in a custom request header named 'X-USERNAME'.
Third party packagesThe following third-party packages are also available. django-rest-knoxDjango-rest-knox library provides models and views to handle token-based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into). The Django OAuth Toolkit package provides OAuth 2.0 support and works with Python 3.4+. The package is maintained by jazzband and uses the excellent OAuthLib. The package is well documented, and well supported and is currently our recommended package for OAuth 2.0 support. Installation & configurationInstall using
Add the package to your
For more details see the Django REST framework - Getting started documentation. Django REST framework OAuthThe Django REST framework OAuth package provides both OAuth2 and OAuth2 support for REST framework. This package was previously included directly in the REST framework but is now supported and maintained as a third-party package. Installation & configurationInstall the package using
For details on configuration and usage see the Django REST framework OAuth documentation for authentication and permissions. JSON Web Token AuthenticationJSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. A package for JWT authentication is djangorestframework-simplejwt which provides some features as well as a pluggable token blacklist app. Hawk HTTP AuthenticationThe HawkREST library builds on the Mohawk library to let you work with Hawk signed requests and responses in your API. Hawk lets two parties securely communicate with each other using messages signed by a shared key. It is based on HTTP MAC access authentication (which was based on parts of OAuth 1.0). HTTP Signature AuthenticationHTTP Signature (currently a IETF draft) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to Amazon's HTTP Signature scheme, used by many of its services, it permits stateless, per-request authentication. Elvio Toccalino maintains the djangorestframework-httpsignature (outdated) package which provides an easy to use HTTP Signature Authentication mechanism. You can use the updated fork version of djangorestframework-httpsignature, which is drf-httpsig. DjoserDjoser library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and uses token-based authentication. This is ready to use REST implementation of the Django authentication system. django-rest-auth / dj-rest-authThis library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management. There are currently two forks of this project.
Drf-social-oauth2 is a framework that helps you authenticate with major social oauth2 vendors, such as Facebook, Google, Twitter, Orcid, etc. It generates tokens in a JWTed way with an easy setup. drfpasswordlessdrfpasswordless adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number. django-rest-authemaildjango-rest-authemail provides a RESTful API interface for user signup and authentication. Email addresses are used for authentication, rather than usernames. API endpoints are available for signup, signup email verification, login, logout, password reset, password reset verification, email change, email change verification, password change, and user detail. A fully functional example project and detailed instructions are included. Django-Rest-DurinDjango-Rest-Durin is built with the idea to have one library that does token auth for multiple Web/CLI/Mobile API clients via one interface but allows different token configuration for each API Client that consumes the API. It provides support for multiple tokens per user via custom models, views, permissions that work with Django-Rest-Framework. The token expiration time can be different per API client and is customizable via the Django Admin Interface. More information can be found in the Documentation. |