<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>The default authentication schemes may be set globally, using the <code>DEFAULT_AUTHENTICATION</code> setting. For example.</p>
<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>
<preclass="prettyprint lang-py"><code># this can go in either server config, virtual host, directory or .htaccess
<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, include <code>rest_framework.authtoken</code> in your <code>INSTALLED_APPS</code> setting:</p>
<p>Make sure to run <code>manage.py syncdb</code> after changing your settings. The <code>authtoken</code> database tables are managed by south (see <ahref="#schema-migrations">Schema migrations</a> below).</p>
<p>You'll also need to create tokens for your users.</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>The <code>curl</code> command line tool may be useful for testing token authenticated APIs. For example:</p>
<preclass="prettyprint lang-py"><code>curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'
</code></pre>
<hr/>
<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>
<preclass="prettyprint lang-py"><code>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)
</code></pre>
<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>
<h4id="schema-migrations">Schema migrations</h4>
<p>The <code>rest_framework.authtoken</code> app includes a south migration that will create the authtoken table.</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>
<preclass="prettyprint lang-py"><code>python manage.py syncdb --noinput # Won't create a superuser just yet, due to `--noinput`.
<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/contrib/csrf/#ajax">Django CSRF documentation</a> for more details.</p>
<p>This authentication uses <ahref="http://oauth.net/core/1.0a">OAuth 1.0a</a> authentication scheme. OAuth 1.0a provides signature validation which provides a reasonable level of security over plain non-HTTPS connections. However, it may also be considered more complicated than OAuth2, as it requires clients to sign their requests.</p>
<p>This authentication class depends on the optional <code>django-oauth-plus</code> and <code>oauth2</code> packages. In order to make it work you must install these packages and add <code>oauth_provider</code> to your <code>INSTALLED_APPS</code>:</p>
<h4id="getting-started-with-django-oauth-plus">Getting started with django-oauth-plus</h4>
<p>The OAuthAuthentication class only provides token verification and signature validation for requests. It doesn't provide authorization flow for your clients. You still need to implement your own views for accessing and authorizing tokens.</p>
<p>The <code>django-oauth-plus</code> package provides simple foundation for classic 'three-legged' oauth flow. Please refer to <ahref="http://code.larlet.fr/django-oauth-plus">the documentation</a> for more details.</p>
<p>This authentication uses <ahref="http://tools.ietf.org/html/rfc6749">OAuth 2.0</a> authentication scheme. OAuth2 is more simple to work with than OAuth1, and provides much better security than simple token authentication. It is an unauthenticated scheme, and requires you to use an HTTPS connection.</p>
<p>This authentication class depends on the optional <ahref="https://github.com/caffeinehit/django-oauth2-provider">django-oauth2-provider</a> project. In order to make it work you must install this package and add <code>provider</code> and <code>provider.oauth2</code> to your <code>INSTALLED_APPS</code>:</p>
<p><strong>Note:</strong> If you use <code>OAuth2Authentication</code> in production you must ensure that your API is only available over <code>https</code>.</p>
<hr/>
<h4id="getting-started-with-django-oauth2-provider">Getting started with django-oauth2-provider</h4>
<p>The <code>OAuth2Authentication</code> class only provides token verification for requests. It doesn't provide authorization flow for your clients.</p>
<p>The OAuth 2 authorization flow is taken care by the <ahref="https://github.com/caffeinehit/django-oauth2-provider">django-oauth2-provider</a> dependency. A walkthrough is given here, but for more details you should refer to <ahref="https://django-oauth2-provider.readthedocs.org/en/latest/">the documentation</a>.</p>
<p>To get started:</p>
<h5id="1-create-a-client">1. Create a client</h5>
<p>You can create a client, either through the shell, or by using the Django admin.</p>
<p>Go to the admin panel and create a new <code>Provider.Client</code> entry. It will create the <code>client_id</code> and <code>client_secret</code> properties for you.</p>
<h5id="2-request-an-access-token">2. Request an access token</h5>
<p>To request an access token, submit a <code>POST</code> request to the url <code>/oauth2/access_token</code> with the following fields:</p>
<ul>
<li><code>client_id</code> the client id you've just configured at the previous step.</li>
<li><code>client_secret</code> again configured at the previous step.</li>
<li><code>username</code> the username with which you want to log in.</li>
<li><code>password</code> well, that speaks for itself.</li>
</ul>
<p>You can use the command line to test that your local configuration is working:</p>
<preclass="prettyprint lang-py"><code>curl -X POST -d "client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=password&username=YOUR_USERNAME&password=YOUR_PASSWORD" http://localhost:8000/oauth2/access_token/
</code></pre>
<p>You should get a response that looks something like this:</p>
<p>The only thing needed to make the <code>OAuth2Authentication</code> class work is to insert the <code>access_token</code> you've received in the <code>Authorization</code> request header.</p>
<p>The command line to test the authentication looks like:</p>
<p>Note that <ahref="https://github.com/evonove/django-oauth-toolkit">Django OAuth Toolkit</a> is an alternative external package that also includes OAuth 2.0 support for REST framework.</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>
<preclass="prettyprint lang-py"><code>from django.contrib.auth.models import User
from rest_framework import authentication
from rest_framework import exceptions
class ExampleAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
username = request.META.get('X_USERNAME')
if not username:
return None
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
raise exceptions.AuthenticationFailed('No such user')
return (user, None)
</code></pre>
<hr/>
<h1id="third-party-packages">Third party packages</h1>
<p>The following third party packages are also available.</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/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 excelllent <ahref="https://github.com/idan/oauthlib">OAuthLib</a>. The package is well documented, and comes as a recommended alternative for OAuth 2.0 support.</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>
</div><!--/span-->
</div><!--/row-->
</div><!--/.fluid-container-->
</div><!--/.body content-->
<divid="push"></div>
</div><!--/.wrapper -->
<footerclass="span12">
<p>Sponsored by <ahref="http://dabapps.com/">DabApps</a>.</a></p>