<p>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 <ahref="../permissions">permission</a> and <ahref="../throttling">throttling</a> policies can then use those credentials to determine if the request should be permitted.</p>
<p>REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.</p>
<p>Authentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.</p>
<p>The <code>request.user</code> property will typically be set to an instance of the <code>contrib.auth</code> package's <code>User</code> class.</p>
<p>The <code>request.auth</code> 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.</p>
<hr/>
<p><strong>Note:</strong> Don't forget that <strong>authentication by itself won't allow or disallow an incoming request</strong>, it simply identifies the credentials that the request was made with.</p>
<h2id="how-authentication-is-determined">How authentication is determined</h2>
<p>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 <code>request.user</code> and <code>request.auth</code> using the return value of the first class that successfully authenticates.</p>
<p>If no class authenticates, <code>request.user</code> will be set to an instance of <code>django.contrib.auth.models.AnonymousUser</code>, and <code>request.auth</code> will be set to <code>None</code>.</p>
<p>The value of <code>request.user</code> and <code>request.auth</code> for unauthenticated requests can be modified using the <code>UNAUTHENTICATED_USER</code> and <code>UNAUTHENTICATED_TOKEN</code> settings.</p>
<h2id="setting-the-authentication-scheme">Setting the authentication scheme</h2>
<p>HTTP 401 responses must always include a <code>WWW-Authenticate</code> header, that instructs the client how to authenticate. HTTP 403 responses do not include the <code>WWW-Authenticate</code> header.</p>
<p>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. <strong>The first authentication class set on the view is used when determining the type of response</strong>.</p>
<p>Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a <code>403 Permission Denied</code> response will always be used, regardless of the authentication scheme.</p>
<h2id="apache-mod_wsgi-specific-configuration">Apache mod_wsgi specific configuration</h2>
<p>Note that if deploying to <ahref="http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPassAuthorization">Apache using mod_wsgi</a>, 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.</p>
<p>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 <code>WSGIPassAuthorization</code> directive in the appropriate context and setting it to <code>'On'</code>.</p>
<p>This authentication scheme uses <ahref="http://tools.ietf.org/html/rfc2617">HTTP Basic Authentication</a>, signed against a user's username and password. Basic authentication is generally only appropriate for testing.</p>
<p>If successfully authenticated, <code>BasicAuthentication</code> provides the following credentials.</p>
<ul>
<li><code>request.user</code> will be a Django <code>User</code> instance.</li>
<li><code>request.auth</code> will be <code>None</code>.</li>
</ul>
<p>Unauthenticated responses that are denied permission will result in an <code>HTTP 401 Unauthorized</code> response with an appropriate WWW-Authenticate header. For example:</p>
<p><strong>Note:</strong> If you use <code>BasicAuthentication</code> in production you must ensure that your API is only available over <code>https</code>. 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.</p>
<p>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.</p>
<p>To use the <code>TokenAuthentication</code> scheme you'll need to <ahref="#setting-the-authentication-scheme">configure the authentication classes</a> to include <code>TokenAuthentication</code>, and additionally include <code>rest_framework.authtoken</code> in your <code>INSTALLED_APPS</code> setting:</p>
<p><strong>Note:</strong> Make sure to run <code>manage.py syncdb</code> after changing your settings. The <code>rest_framework.authtoken</code> app provides both Django (from v1.7) and South database migrations. See <ahref="#schema-migrations">Schema migrations</a> below.</p>
<p>For clients to authenticate, the token key should be included in the <code>Authorization</code> HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings. For example:</p>
<p>If successfully authenticated, <code>TokenAuthentication</code> provides the following credentials.</p>
<ul>
<li><code>request.user</code> will be a Django <code>User</code> instance.</li>
<li><code>request.auth</code> will be a <code>rest_framework.authtoken.models.BasicToken</code> instance.</li>
</ul>
<p>Unauthenticated responses that are denied permission will result in an <code>HTTP 401 Unauthorized</code> response with an appropriate WWW-Authenticate header. For example:</p>
<p><strong>Note:</strong> If you use <code>TokenAuthentication</code> in production you must ensure that your API is only available over <code>https</code>.</p>
<hr/>
<h4id="generating-tokens">Generating Tokens</h4>
<p>If you want every user to have an automatically generated Token, you can simply catch the User's <code>post_save</code> signal.</p>
<p>Note that you'll want to ensure you place this code snippet in an installed <code>models.py</code> module, or some other location that will be imported by Django on startup.</p>
<p>If you've already created some users, you can generate tokens for all existing users like this:</p>
<p>When using <code>TokenAuthentication</code>, 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 behavior. To use it, add the <code>obtain_auth_token</code> view to your URLconf:</p>
<p>Note that the URL part of the pattern can be whatever you want to use.</p>
<p>The <code>obtain_auth_token</code> view will return a JSON response when valid <code>username</code> and <code>password</code> fields are POSTed to the view using form data or JSON:</p>
<p>Note that the default <code>obtain_auth_token</code> view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of the <code>obtain_auth_token</code> view, you can do so by overriding the <code>ObtainAuthToken</code> view class, and using that in your url conf instead.</p>
<p>The <code>rest_framework.authtoken</code> app includes both Django native migrations (for Django versions >1.7) and South migrations (for Django versions <1.7) that will create the authtoken table.</p>
<hr/>
<p><strong>Note</strong>: From REST Framework v2.4.0 using South with Django <1.7 requires upgrading South v1.0+</p>
<p>If you're using a <ahref="https://docs.djangoproject.com/en/dev/topics/auth/customizing/#specifying-a-custom-user-model">custom user model</a> you'll need to make sure that any initial migration that creates the user table runs before the authtoken table is created.</p>
<p>You can do so by inserting a <code>needed_by</code> attribute in your user migration:</p>
<p>For more details, see the <ahref="http://south.readthedocs.org/en/latest/dependencies.html">south documentation on dependencies</a>.</p>
<p>Also note that if you're using a <code>post_save</code> signal to create tokens, then the first time you create the database tables, you'll need to ensure any migrations are run prior to creating any superusers. For example:</p>
<p>This 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.</p>
<p>If successfully authenticated, <code>SessionAuthentication</code> provides the following credentials.</p>
<ul>
<li><code>request.user</code> will be a Django <code>User</code> instance.</li>
<li><code>request.auth</code> will be <code>None</code>.</li>
</ul>
<p>Unauthenticated responses that are denied permission will result in an <code>HTTP 403 Forbidden</code> response.</p>
<p>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 <code>PUT</code>, <code>PATCH</code>, <code>POST</code> or <code>DELETE</code> requests. See the <ahref="https://docs.djangoproject.com/en/dev/ref/csrf/#ajax">Django CSRF documentation</a> for more details.</p>
<p>To implement a custom authentication scheme, subclass <code>BaseAuthentication</code> and override the <code>.authenticate(self, request)</code> method. The method should return a two-tuple of <code>(user, auth)</code> if authentication succeeds, or <code>None</code> otherwise.</p>
<p>In some circumstances instead of returning <code>None</code>, you may want to raise an <code>AuthenticationFailed</code> exception from the <code>.authenticate()</code> method.</p>
<p>Typically the approach you should take is:</p>
<ul>
<li>If authentication is not attempted, return <code>None</code>. Any other authentication schemes also in use will still be checked.</li>
<li>If authentication is attempted but fails, raise a <code>AuthenticationFailed</code> exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.</li>
</ul>
<p>You <em>may</em> also override the <code>.authenticate_header(self, request)</code> method. If implemented, it should return a string that will be used as the value of the <code>WWW-Authenticate</code> header in a <code>HTTP 401 Unauthorized</code> response.</p>
<p>If the <code>.authenticate_header()</code> method is not overridden, the authentication scheme will return <code>HTTP 403 Forbidden</code> responses when an unauthenticated request is denied access.</p>
<h2id="example">Example</h2>
<p>The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X_USERNAME'.</p>
<p>The <ahref="https://github.com/evonove/django-oauth-toolkit">Django OAuth Toolkit</a> package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by <ahref="https://github.com/evonove/">Evonove</a> and uses the excellent <ahref="https://github.com/idan/oauthlib">OAuthLib</a>. The package is well documented, and well supported and is currently our <strong>recommended package for OAuth 2.0 support</strong>.</p>
<h4id="installation-configuration">Installation & configuration</h4>
<p>Install using <code>pip</code>.</p>
<pre><code>pip install django-oauth-toolkit
</code></pre>
<p>Add the package to your <code>INSTALLED_APPS</code> and modify your REST framework settings.</p>
<p>For more details see the <ahref="https://django-oauth-toolkit.readthedocs.org/en/latest/rest-framework/getting_started.html">Django REST framework - Getting started</a> documentation.</p>
<p>The <ahref="http://jpadilla.github.io/django-rest-framework-oauth/">Django REST framework OAuth</a> package provides both OAuth1 and OAuth2 support for REST framework.</p>
<p>This package was previously included directly in REST framework but is now supported and maintained as a third party package.</p>
<h4id="installation-configuration_1">Installation & configuration</h4>
<p>Install the package using <code>pip</code>.</p>
<pre><code>pip install djangorestframework-oauth
</code></pre>
<p>For details on configuration and usage see the Django REST framework OAuth documentation for <ahref="http://jpadilla.github.io/django-rest-framework-oauth/authentication/">authentication</a> and <ahref="http://jpadilla.github.io/django-rest-framework-oauth/permissions/">permissions</a>.</p>
<p>HTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. <ahref="https://github.com/juanriaza">Juan Riaza</a> maintains the <ahref="https://github.com/juanriaza/django-rest-framework-digestauth">djangorestframework-digestauth</a> package which provides HTTP digest authentication support for REST framework.</p>
<p>The <ahref="https://github.com/Rediker-Software/doac">Django OAuth2 Consumer</a> library from <ahref="https://github.com/Rediker-Software">Rediker Software</a> is another package that provides <ahref="https://github.com/Rediker-Software/doac/blob/master/docs/integrations.md#">OAuth 2.0 support for REST framework</a>. The package includes token scoping permissions on tokens, which allows finer-grained access to your API.</p>
<h2id="json-web-token-authentication">JSON Web Token Authentication</h2>
<p>JSON 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. <ahref="https://github.com/GetBlimp">Blimp</a> maintains the <ahref="https://github.com/GetBlimp/django-rest-framework-jwt">djangorestframework-jwt</a> package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password.</p>
<p>The <ahref="http://hawkrest.readthedocs.org/en/latest/">HawkREST</a> library builds on the <ahref="http://mohawk.readthedocs.org/en/latest/">Mohawk</a> library to let you work with <ahref="https://github.com/hueniverse/hawk">Hawk</a> signed requests and responses in your API. <ahref="https://github.com/hueniverse/hawk">Hawk</a> lets two parties securely communicate with each other using messages signed by a shared key. It is based on <ahref="http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05">HTTP MAC access authentication</a> (which was based on parts of <ahref="http://oauth.net/core/1.0a">OAuth 1.0</a>).</p>
<p><ahref="https://github.com/sunscrapers/djoser">Djoser</a> 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 it uses token based authentication. This is a ready to use REST implementation of Django authentication system.</p>
<p><ahref="https://github.com/Tivix/django-rest-auth">Django-rest-auth</a> 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.</p>