diff --git a/api-guide/authentication/index.html b/api-guide/authentication/index.html index 760e9ec35..c5cc62dd3 100644 --- a/api-guide/authentication/index.html +++ b/api-guide/authentication/index.html @@ -467,6 +467,10 @@ +
Note: If you use BasicAuthentication
in production you must ensure that your API is only available over https
. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.
Note: 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 TokenAuthentication
scheme you'll need to configure the authentication classes to include TokenAuthentication
, and additionally include rest_framework.authtoken
in your INSTALLED_APPS
setting:
INSTALLED_APPS = [
@@ -628,9 +632,8 @@ WSGIPassAuthorization On
'rest_framework.authtoken'
]
-Note: Make sure to run manage.py migrate
after changing your settings. The rest_framework.authtoken
app provides Django database migrations.
Make sure to run manage.py migrate
after changing your settings.
The rest_framework.authtoken
app provides Django database migrations.
You'll also need to create tokens for your users.
from rest_framework.authtoken.models import Token
@@ -640,7 +643,7 @@ print(token.key)
For clients to authenticate, the token key should be included in the Authorization
HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings. For example:
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
-Note: If you want to use a different keyword in the header, such as Bearer
, simply subclass TokenAuthentication
and set the keyword
class variable.
+If you want to use a different keyword in the header, such as Bearer
, simply subclass TokenAuthentication
and set the keyword
class variable.
If successfully authenticated, TokenAuthentication
provides the following credentials.
request.user
will be a Django User
instance.
@@ -795,6 +798,8 @@ class ExampleAuthentication(authentication.BaseAuthentication):
Third party packages
The following third-party packages are also available.
+django-rest-knox
+Django-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).
Django OAuth Toolkit
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 & configuration
@@ -837,10 +842,8 @@ REST_FRAMEWORK = {
- Django-rest-auth is the original project, but is not currently receiving updates.
- Dj-rest-auth is a newer fork of the project.
-django-rest-framework-social-oauth2
-Django-rest-framework-social-oauth2 library provides an easy way to integrate social plugins (facebook, twitter, google, etc.) to your authentication system and an easy oauth2 setup. With this library, you will be able to authenticate users based on external tokens (e.g. facebook access token), convert these tokens to "in-house" oauth2 tokens and use and generate oauth2 tokens to authenticate your users.
-django-rest-knox
-Django-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).
+drf-social-oauth2
+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.
drfpasswordless
drfpasswordless 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-authemail
diff --git a/api-guide/fields/index.html b/api-guide/fields/index.html
index c886d2b42..1de323753 100644
--- a/api-guide/fields/index.html
+++ b/api-guide/fields/index.html
@@ -664,7 +664,7 @@
Normally an error will be raised if a field is not supplied during deserialization.
Set to false if this field is not required to be present during deserialization.
Setting this to False
also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.
-Defaults to True
.
+Defaults to True
. If you're using Model Serializer default value will be False
if you have specified blank=True
or default
or null=True
at your field in your Model
.
default
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.
The default
is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.
diff --git a/api-guide/relations/index.html b/api-guide/relations/index.html
index 3e4c2176e..c6cfe73f6 100644
--- a/api-guide/relations/index.html
+++ b/api-guide/relations/index.html
@@ -552,7 +552,7 @@
Note: The relational fields are declared in relations.py
, but by convention you should import them from the serializers
module, using from rest_framework import serializers
and refer to fields as serializers.<FieldName>
.
-Note: REST Framework does not attempt to automatically optimize querysets passed to serializers in terms of select_related
and prefetch_related
since it would be too much magic. A serializer with a field spanning an orm relation through its source attribute could require an additional database hit to fetch related object from the database. It is the programmer's responsibility to optimize queries to avoid additional database hits which could occur while using such a serializer.
+Note: REST Framework does not attempt to automatically optimize querysets passed to serializers in terms of select_related
and prefetch_related
since it would be too much magic. A serializer with a field spanning an orm relation through its source attribute could require an additional database hit to fetch related objects from the database. It is the programmer's responsibility to optimize queries to avoid additional database hits which could occur while using such a serializer.
For example, the following serializer would lead to a database hit each time evaluating the tracks field if it is not prefetched:
class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.SlugRelatedField(
diff --git a/api-guide/testing/index.html b/api-guide/testing/index.html
index f926d8a86..a7d97f957 100644
--- a/api-guide/testing/index.html
+++ b/api-guide/testing/index.html
@@ -614,7 +614,7 @@ request = factory.get('/accounts/django-superstars/')
force_authenticate(request, user=user, token=user.auth_token)
-Note: force_authenticate
directly sets request.user
to the in-memory user
instance. If you are re-using the same user
instance across multiple tests that update the saved user
state, you may need to call refresh_from_db()
between tests.
+Note: force_authenticate
directly sets request.user
to the in-memory user
instance. If you are re-using the same user
instance across multiple tests that update the saved user
state, you may need to call refresh_from_db()
between tests.
Note: When using APIRequestFactory
, the object that is returned is Django's standard HttpRequest
, and not REST framework's Request
object, which is only generated once the view is called.
This means that setting attributes directly on the request object may not always have the effect you expect. For example, setting .token
directly will have no effect, and setting .user
directly will only work if session authentication is being used.
@@ -770,7 +770,7 @@ client.session.headers.update({'x-test': 'true'})
REST framework includes the following test case classes, that mirror the existing Django test case classes, but use APIClient
instead of Django's default Client
.
REST framework includes the following test case classes, that mirror the existing Django's test case classes, but use APIClient
instead of Django's default Client
.
APISimpleTestCase
APITransactionTestCase
Another scenario where you might want to use multiple throttles would be if you need to impose different constraints on different parts of the API, due to some services being particularly resource-intensive.
Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day.
Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed.
-The application-level throttling that REST framework provides should not be considered a security measure or protection against brute forcing or denial-of-service attacks. Deliberately malicious actors will always be able to spoof IP origins, and application-level throttling is intended for implementing policies such as different business tiers and basic protections against service over-use.
+**The application-level throttling that REST framework provides should not be considered a security measure or protection against brute forcing or denial-of-service attacks. Deliberately malicious actors will always be able to spoof IP origins. In addition to this, the built-in throttling implementations are implemented using Django's cache framework, and use non-atomic operations to determine the request rate, which may sometimes result in some fuzziness.
+The application-level throttling provided by REST framework is intended for implementing policies such as different business tiers and basic protections against service over-use.**
As with permissions and authentication, throttling in REST framework is always defined as a list of classes.
Before running the main body of the view each throttle in the list is checked. @@ -554,6 +559,9 @@ class CustomAnonRateThrottle(AnonRateThrottle): cache = caches['alternate']
You'll need to remember to also set your custom throttle class in the 'DEFAULT_THROTTLE_CLASSES'
settings key, or using the throttle_classes
view attribute.
The built-in throttle implementations are open to race conditions, so under high concurrency they may allow a few extra requests through.
+If your project relies on guaranteeing the number of requests during concurrent requests, you will need to implement your own throttle class. See issue #5181 for more details.
There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.
+Note: At this point in it's lifespan we consider Django REST framework to be essentially feature-complete. We may accept pull requests that track the continued development of Django versions, but would prefer not to accept new features or code formatting changes.
+The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case.
If you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a particular JavaScript framework. Experiences from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are more difficult to understand and work with.
@@ -498,13 +501,12 @@Be mindful in the language you choose. As an example, in an environment that is heavily male-dominated, posts that start 'Hey guys,' can come across as unintentionally exclusive. It's just as easy, and more inclusive to use gender neutral language in those situations.
The Django code of conduct gives a fuller set of guidelines for participating in community forums.
It's really helpful if you can make sure to address issues on the correct channel. Usage questions should be directed to the discussion group. Feature requests, bug reports and other issues should be raised on the GitHub issue tracker.
-Some tips on good issue reporting:
+Our contribution process is that the GitHub discussions page should generally be your starting point. Please only raise an issue or pull request if you've been recommended to do so after discussion.
+Some tips on good potential issue reporting:
Many thanks to all our wonderful sponsors, and in particular to our premium backers, Sentry, Stream, ESG, Rollbar, Cadre, Kloudless, Lights On Software, Retool, bit.io, PostHog, and CryptAPI.
+Many thanks to all our wonderful sponsors, and in particular to our premium backers, Sentry, Stream, Cadre, Kloudless, Lights On Software, Retool, bit.io, PostHog, CryptAPI, and FEZTO.
REST framework requires the following:
diff --git a/search/search_index.json b/search/search_index.json index 9e5d3df16..c5976e9c2 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":".promo li a { float: left; width: 130px; height: 20px; text-align: center; margin: 10px 30px; padding: 150px 0 0 0; background-position: 0 50%; background-size: 130px auto; background-repeat: no-repeat; font-size: 120%; color: black; } .promo li { list-style: none; } Django REST Framework Django REST framework is a powerful and flexible toolkit for building Web APIs. Some reasons you might want to use REST framework: The Web browsable API is a huge usability win for your developers. Authentication policies including packages for OAuth1a and OAuth2 . Serialization that supports both ORM and non-ORM data sources. Customizable all the way down - just use regular function-based views if you don't need the more powerful features . Extensive documentation, and great community support . Used and trusted by internationally recognised companies including Mozilla , Red Hat , Heroku , and Eventbrite . Funding REST framework is a collaboratively funded project . If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan . Every single sign-up helps us make REST framework long-term financially sustainable. Sentry Stream ESG Rollbar Retool bit.io PostHog CryptAPI Many thanks to all our wonderful sponsors , and in particular to our premium backers, Sentry , Stream , ESG , Rollbar , Cadre , Kloudless , Lights On Software , Retool , bit.io , PostHog , and CryptAPI . Requirements REST framework requires the following: Python (3.6, 3.7, 3.8, 3.9, 3.10) Django (2.2, 3.0, 3.1, 3.2, 4.0) We highly recommend and only officially support the latest patch release of each Python and Django series. The following packages are optional: PyYAML , uritemplate (5.1+, 3.0.0+) - Schema generation support. Markdown (3.0.0+) - Markdown support for the browsable API. Pygments (2.4.0+) - Add syntax highlighting to Markdown processing. django-filter (1.0.1+) - Filtering support. django-guardian (1.1.1+) - Object level permissions support. Installation Install using pip , including any optional packages you want... pip install djangorestframework pip install markdown # Markdown support for the browsable API. pip install django-filter # Filtering support ...or clone the project from github. git clone https://github.com/encode/django-rest-framework Add 'rest_framework' to your INSTALLED_APPS setting. INSTALLED_APPS = [ ... 'rest_framework', ] If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root urls.py file. urlpatterns = [ ... path('api-auth/', include('rest_framework.urls')) ] Note that the URL path can be whatever you want. Example Let's take a look at a quick example of using REST framework to build a simple model-backed API. We'll create a read-write API for accessing information on the users of our project. Any global settings for a REST framework API are kept in a single configuration dictionary named REST_FRAMEWORK . Start off by adding the following to your settings.py module: REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } Don't forget to make sure you've also added rest_framework to your INSTALLED_APPS . We're ready to create our API now. Here's our project's root urls.py module: from django.urls import path, include from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets # Serializers define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'is_staff'] # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r'users', UserViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] You can now open the API in your browser at http://127.0.0.1:8000/ , and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system. Quickstart Can't wait to get started? The quickstart guide is the fastest way to get up and running, and building APIs with REST framework. Development See the Contribution guidelines for information on how to clone the repository, run the test suite and contribute changes back to REST Framework. Support For support please see the REST framework discussion group , try the #restframework channel on irc.libera.chat , or raise a question on Stack Overflow , making sure to include the 'django-rest-framework' tag. For priority support please sign up for a professional or premium sponsorship plan . Security Security issues are handled under the supervision of the Django security team . Please report security issues by emailing security@djangoproject.com . The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure. License Copyright \u00a9 2011-present, Encode OSS Ltd . All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.","title":"Home"},{"location":"#funding","text":"REST framework is a collaboratively funded project . If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan . Every single sign-up helps us make REST framework long-term financially sustainable. Sentry Stream ESG Rollbar Retool bit.io PostHog CryptAPI Many thanks to all our wonderful sponsors , and in particular to our premium backers, Sentry , Stream , ESG , Rollbar , Cadre , Kloudless , Lights On Software , Retool , bit.io , PostHog , and CryptAPI .","title":"Funding"},{"location":"#requirements","text":"REST framework requires the following: Python (3.6, 3.7, 3.8, 3.9, 3.10) Django (2.2, 3.0, 3.1, 3.2, 4.0) We highly recommend and only officially support the latest patch release of each Python and Django series. The following packages are optional: PyYAML , uritemplate (5.1+, 3.0.0+) - Schema generation support. Markdown (3.0.0+) - Markdown support for the browsable API. Pygments (2.4.0+) - Add syntax highlighting to Markdown processing. django-filter (1.0.1+) - Filtering support. django-guardian (1.1.1+) - Object level permissions support.","title":"Requirements"},{"location":"#installation","text":"Install using pip , including any optional packages you want... pip install djangorestframework pip install markdown # Markdown support for the browsable API. pip install django-filter # Filtering support ...or clone the project from github. git clone https://github.com/encode/django-rest-framework Add 'rest_framework' to your INSTALLED_APPS setting. INSTALLED_APPS = [ ... 'rest_framework', ] If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root urls.py file. urlpatterns = [ ... path('api-auth/', include('rest_framework.urls')) ] Note that the URL path can be whatever you want.","title":"Installation"},{"location":"#example","text":"Let's take a look at a quick example of using REST framework to build a simple model-backed API. We'll create a read-write API for accessing information on the users of our project. Any global settings for a REST framework API are kept in a single configuration dictionary named REST_FRAMEWORK . Start off by adding the following to your settings.py module: REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } Don't forget to make sure you've also added rest_framework to your INSTALLED_APPS . We're ready to create our API now. Here's our project's root urls.py module: from django.urls import path, include from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets # Serializers define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'is_staff'] # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r'users', UserViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] You can now open the API in your browser at http://127.0.0.1:8000/ , and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system.","title":"Example"},{"location":"#quickstart","text":"Can't wait to get started? The quickstart guide is the fastest way to get up and running, and building APIs with REST framework.","title":"Quickstart"},{"location":"#development","text":"See the Contribution guidelines for information on how to clone the repository, run the test suite and contribute changes back to REST Framework.","title":"Development"},{"location":"#support","text":"For support please see the REST framework discussion group , try the #restframework channel on irc.libera.chat , or raise a question on Stack Overflow , making sure to include the 'django-rest-framework' tag. For priority support please sign up for a professional or premium sponsorship plan .","title":"Support"},{"location":"#security","text":"Security issues are handled under the supervision of the Django security team . Please report security issues by emailing security@djangoproject.com . The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.","title":"Security"},{"location":"#license","text":"Copyright \u00a9 2011-present, Encode OSS Ltd . All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.","title":"License"},{"location":"api-guide/authentication/","text":"Authentication Auth needs to be pluggable. \u2014 Jacob Kaplan-Moss, \"REST worst practices\" 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 request.user property will typically be set to an instance of the contrib.auth package's User class. The request.auth property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with. 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 determined The 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 request.user and request.auth using the return value of the first class that successfully authenticates. If no class authenticates, request.user will be set to an instance of django.contrib.auth.models.AnonymousUser , and request.auth will be set to None . The value of request.user and request.auth for unauthenticated requests can be modified using the UNAUTHENTICATED_USER and UNAUTHENTICATED_TOKEN settings. Setting the authentication scheme The default authentication schemes may be set globally, using the DEFAULT_AUTHENTICATION_CLASSES setting. For example. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ] } You can also set the authentication scheme on a per-view or per-viewset basis, using the APIView class-based views. from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def get(self, request, format=None): content = { 'user': str(request.user), # `django.contrib.auth.User` instance. 'auth': str(request.auth), # None } return Response(content) Or, if you're using the @api_view decorator with function based views. @api_view(['GET']) @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def example_view(request, format=None): content = { 'user': str(request.user), # `django.contrib.auth.User` instance. 'auth': str(request.auth), # None } return Response(content) Unauthorized and Forbidden responses When an unauthenticated request is denied permission there are two different error codes that may be appropriate. HTTP 401 Unauthorized HTTP 403 Permission Denied HTTP 401 responses must always include a WWW-Authenticate header, that instructs the client how to authenticate. HTTP 403 responses do not include the WWW-Authenticate header. 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 403 Permission Denied response will always be used, regardless of the authentication scheme. Apache mod_wsgi specific configuration Note 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 WSGIPassAuthorization directive in the appropriate context and setting it to 'On' . # this can go in either server config, virtual host, directory or .htaccess WSGIPassAuthorization On API Reference BasicAuthentication This 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, BasicAuthentication provides the following credentials. request.user will be a Django User instance. request.auth will be None . Unauthenticated responses that are denied permission will result in an HTTP 401 Unauthorized response with an appropriate WWW-Authenticate header. For example: WWW-Authenticate: Basic realm=\"api\" Note: If you use BasicAuthentication in production you must ensure that your API is only available over https . You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage. TokenAuthentication 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 TokenAuthentication scheme you'll need to configure the authentication classes to include TokenAuthentication , and additionally include rest_framework.authtoken in your INSTALLED_APPS setting: INSTALLED_APPS = [ ... 'rest_framework.authtoken' ] Note: Make sure to run manage.py migrate after changing your settings. The rest_framework.authtoken app provides Django database migrations. You'll also need to create tokens for your users. from rest_framework.authtoken.models import Token token = Token.objects.create(user=...) print(token.key) For clients to authenticate, the token key should be included in the Authorization HTTP header. The key should be prefixed by the string literal \"Token\", with whitespace separating the two strings. For example: Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b Note: If you want to use a different keyword in the header, such as Bearer , simply subclass TokenAuthentication and set the keyword class variable. If successfully authenticated, TokenAuthentication provides the following credentials. request.user will be a Django User instance. request.auth will be a rest_framework.authtoken.models.Token instance. Unauthenticated responses that are denied permission will result in an HTTP 401 Unauthorized response with an appropriate WWW-Authenticate header. For example: WWW-Authenticate: Token The curl command line tool may be useful for testing token authenticated APIs. For example: curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' Note: If you use TokenAuthentication in production you must ensure that your API is only available over https . Generating Tokens By using signals If you want every user to have an automatically generated Token, you can simply catch the User's post_save signal. from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) Note that you'll want to ensure you place this code snippet in an installed models.py module, or some other location that will be imported by Django on startup. If you've already created some users, you can generate tokens for all existing users like this: from django.contrib.auth.models import User from rest_framework.authtoken.models import Token for user in User.objects.all(): Token.objects.get_or_create(user=user) By exposing an api endpoint When using TokenAuthentication , you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behaviour. To use it, add the obtain_auth_token view to your URLconf: from rest_framework.authtoken import views urlpatterns += [ path('api-token-auth/', views.obtain_auth_token) ] Note that the URL part of the pattern can be whatever you want to use. The obtain_auth_token view will return a JSON response when valid username and password fields are POSTed to the view using form data or JSON: { 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' } Note that the default obtain_auth_token view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. By default, there are no permissions or throttling applied to the obtain_auth_token view. If you do wish to apply to throttle you'll need to override the view class, and include them using the throttle_classes attribute. If you need a customized version of the obtain_auth_token view, you can do so by subclassing the ObtainAuthToken view class, and using that in your url conf instead. For example, you may return additional user information beyond the token value: from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.authtoken.models import Token from rest_framework.response import Response class CustomAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'user_id': user.pk, 'email': user.email }) And in your urls.py : urlpatterns += [ path('api-token-auth/', CustomAuthToken.as_view()) ] With Django admin It 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 TokenAdmin class customize it to your needs, more specifically by declaring the user field as raw_field . your_app/admin.py : from rest_framework.authtoken.admin import TokenAdmin TokenAdmin.raw_id_fields = ['user'] Using Django manage.py command Since version 3.6.4 it's possible to generate a user token using the following command: ./manage.py drf_create_token