django-rest-framework/docs/api-guide/authentication.md

368 lines
18 KiB
Markdown
Raw Normal View History

2012-09-09 01:06:13 +04:00
<a class="github" href="authentication.py"></a>
2012-09-05 13:01:43 +04:00
# Authentication
2012-09-12 13:12:13 +04:00
> Auth needs to be pluggable.
>
> &mdash; Jacob Kaplan-Moss, ["REST worst practices"][cite]
2012-09-05 16:03:55 +04:00
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.
2012-10-17 17:59:53 +04:00
REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.
2012-09-05 13:01:43 +04:00
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.
2012-09-05 16:03:55 +04:00
2012-09-06 00:14:00 +04:00
The `request.user` property will typically be set to an instance of the `contrib.auth` package's `User` class.
2012-09-07 22:12:46 +04:00
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.
2012-09-06 00:14:00 +04:00
---
2013-01-22 01:29:49 +04:00
**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 setup the permission polices for your API please see the [permissions documentation][permission].
---
2012-09-05 23:10:06 +04:00
## How authentication is determined
2012-10-17 17:59:53 +04:00
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.
2012-09-05 23:10:06 +04:00
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`.
2012-09-06 00:14:00 +04:00
The value of `request.user` and `request.auth` for unauthenticated requests can be modified using the `UNAUTHENTICATED_USER` and `UNAUTHENTICATED_TOKEN` settings.
2012-09-05 23:10:06 +04:00
2012-10-17 17:59:53 +04:00
## Setting the authentication scheme
2012-09-05 16:03:55 +04:00
2012-10-17 17:59:53 +04:00
The default authentication schemes may be set globally, using the `DEFAULT_AUTHENTICATION` setting. For example.
2012-09-05 16:03:55 +04:00
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
2012-09-05 16:03:55 +04:00
)
}
You can also set the authentication scheme on a per-view or per-viewset basis,
using the `APIView` class based views.
2012-09-05 16:03:55 +04:00
class ExampleView(APIView):
authentication_classes = (SessionAuthentication, BasicAuthentication)
2012-09-30 18:55:24 +04:00
permission_classes = (IsAuthenticated,)
2012-09-05 16:03:55 +04:00
def get(self, request, format=None):
content = {
2012-09-07 22:12:46 +04:00
'user': unicode(request.user), # `django.contrib.auth.User` instance.
2012-09-05 16:03:55 +04:00
'auth': unicode(request.auth), # None
}
return Response(content)
Or, if you're using the `@api_view` decorator with function based views.
2012-10-29 12:25:17 +04:00
@api_view(['GET'])
@authentication_classes((SessionAuthentication, BasicAuthentication))
2013-01-11 23:26:44 +04:00
@permission_classes((IsAuthenticated,))
2012-09-05 16:03:55 +04:00
def example_view(request, format=None):
content = {
2012-09-07 22:12:46 +04:00
'user': unicode(request.user), # `django.contrib.auth.User` instance.
2012-09-05 16:03:55 +04:00
'auth': unicode(request.auth), # None
}
return Response(content)
2012-10-17 17:59:53 +04:00
## Unauthorized and Forbidden responses
When an unauthenticated request is denied permission there are two different error codes that may be appropriate.
* [HTTP 401 Unauthorized][http401]
* [HTTP 403 Permission Denied][http403]
2013-01-22 01:29:49 +04:00
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.
2012-10-17 17:59:53 +04:00
2013-01-22 01:29:49 +04:00
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**.
2012-10-17 17:59:53 +04:00
2013-01-22 01:29:49 +04:00
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.
2012-10-17 17:59:53 +04:00
2013-01-19 02:26:36 +04:00
## Apache mod_wsgi specific configuration
2013-01-19 02:26:36 +04:00
Note that if deploying to [Apache using mod_wsgi][mod_wsgi_official], 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.
2013-05-28 19:13:12 +04:00
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
2012-10-17 17:59:53 +04:00
---
2012-10-15 16:27:50 +04:00
# API Reference
2012-09-12 23:39:22 +04:00
## BasicAuthentication
2012-09-05 16:03:55 +04:00
2012-10-17 17:59:53 +04:00
This authentication scheme uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. Basic authentication is generally only appropriate for testing.
2012-09-05 16:03:55 +04:00
2012-09-12 23:39:22 +04:00
If successfully authenticated, `BasicAuthentication` provides the following credentials.
2012-09-05 16:03:55 +04:00
2012-11-20 01:42:33 +04:00
* `request.user` will be a Django `User` instance.
2012-09-05 16:03:55 +04:00
* `request.auth` will be `None`.
2012-09-05 13:01:43 +04:00
2012-10-17 18:10:11 +04:00
Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example:
2012-10-17 17:59:53 +04:00
WWW-Authenticate: Basic realm="api"
2013-04-11 09:00:40 +04:00
**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.
2012-09-12 23:39:22 +04:00
2012-09-07 22:12:46 +04:00
## TokenAuthentication
2012-09-05 13:01:43 +04:00
2013-03-09 04:31:19 +04:00
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.
2012-09-12 23:39:22 +04:00
2013-03-05 18:02:58 +04:00
To use the `TokenAuthentication` scheme, include `rest_framework.authtoken` in your `INSTALLED_APPS` setting:
INSTALLED_APPS = (
...
'rest_framework.authtoken'
)
2013-03-28 18:54:42 +04:00
Make sure to run `manage.py syncdb` after changing your settings.
2012-09-12 23:39:22 +04:00
You'll also need to create tokens for your users.
from rest_framework.authtoken.models import Token
2012-09-12 13:12:13 +04:00
2012-09-12 23:39:22 +04:00
token = Token.objects.create(user=...)
print token.key
2012-09-05 16:03:55 +04:00
2012-10-21 18:34:07 +04:00
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:
2012-09-05 16:03:55 +04:00
2012-09-12 23:39:22 +04:00
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
2012-09-07 22:12:46 +04:00
If successfully authenticated, `TokenAuthentication` provides the following credentials.
2012-09-05 16:03:55 +04:00
2012-11-20 01:42:33 +04:00
* `request.user` will be a Django `User` instance.
* `request.auth` will be a `rest_framework.authtoken.models.BasicToken` instance.
2012-09-07 22:12:46 +04:00
2012-10-17 18:10:11 +04:00
Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example:
2012-10-17 17:59:53 +04:00
WWW-Authenticate: Token
2012-09-07 22:12:46 +04:00
2013-03-28 18:54:42 +04:00
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'
2013-03-05 21:39:34 +04:00
---
2013-04-11 09:00:40 +04:00
**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https`.
2012-09-05 16:03:55 +04:00
---
2013-03-05 21:39:34 +04:00
#### Generating Tokens
If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
@receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
2012-11-20 02:08:38 +04:00
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)
2013-03-05 21:39:34 +04:00
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 behavior. To use it, add the `obtain_auth_token` view to your URLconf:
urlpatterns += patterns('',
2012-11-28 13:58:34 +04:00
url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token')
)
2012-11-20 02:08:38 +04:00
Note that the URL part of the pattern can be whatever you want to use.
2012-11-20 01:42:33 +04:00
2012-11-20 02:08:38 +04:00
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. If you need a customized version of the `obtain_auth_token` view, you can do so by overriding the `ObtainAuthToken` view class, and using that in your url conf instead.
2013-03-05 21:39:34 +04:00
#### Custom user models
The `rest_framework.authtoken` app includes a south migration that will create the authtoken table. If you're using a [custom user model][custom-user-model] you'll need to make sure that any initial migration that creates the user table runs before the authtoken table is created.
You can do so by inserting a `needed_by` attribute in your user migration:
class Migration:
needed_by = (
('authtoken', '0001_initial'),
)
def forwards(self):
...
2013-03-05 21:42:31 +04:00
For more details, see the [south documentation on dependencies][south-dependencies].
2012-09-05 13:01:43 +04:00
## SessionAuthentication
2012-09-05 16:03:55 +04:00
2012-10-17 17:59:53 +04:00
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.
2012-09-05 16:03:55 +04:00
If successfully authenticated, `SessionAuthentication` provides the following credentials.
2012-11-20 01:42:33 +04:00
* `request.user` will be a Django `User` instance.
2012-09-05 16:03:55 +04:00
* `request.auth` will be `None`.
2012-10-17 17:59:53 +04:00
Unauthenticated responses that are denied permission will result in an `HTTP 403 Forbidden` response.
2013-01-17 15:17:53 +04:00
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 `PUT`, `PATCH`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
## OAuthAuthentication
2013-05-28 19:13:12 +04:00
This authentication uses [OAuth 1.0a][oauth-1.0a] 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.
2013-03-09 04:31:19 +04:00
2013-05-28 19:13:12 +04:00
This authentication class depends on the optional `django-oauth-plus` and `oauth2` packages. In order to make it work you must install these packages and add `oauth_provider` to your `INSTALLED_APPS`:
INSTALLED_APPS = (
2013-03-07 21:43:13 +04:00
...
`oauth_provider`,
)
2013-03-09 04:31:19 +04:00
Don't forget to run `syncdb` once you've added the package.
python manage.py syncdb
2013-03-07 21:43:13 +04:00
#### Getting started with django-oauth-plus
2013-05-28 19:13:12 +04:00
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.
2013-03-09 04:31:19 +04:00
The `django-oauth-plus` package provides simple foundation for classic 'three-legged' oauth flow. Please refer to [the documentation][django-oauth-plus] for more details.
2013-03-07 21:43:13 +04:00
## OAuth2Authentication
2013-03-09 04:31:19 +04:00
This authentication uses [OAuth 2.0][rfc6749] 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.
2013-05-28 19:13:12 +04:00
This authentication class depends on the optional [django-oauth2-provider][django-oauth2-provider] project. In order to make it work you must install this package and add `provider` and `provider.oauth2` to your `INSTALLED_APPS`:
2013-03-01 05:09:52 +04:00
INSTALLED_APPS = (
2013-03-07 21:43:13 +04:00
...
2013-03-01 05:09:52 +04:00
'provider',
'provider.oauth2',
)
2013-03-09 04:31:19 +04:00
You must also include the following in your root `urls.py` module:
2013-03-01 05:09:52 +04:00
2013-03-07 21:43:13 +04:00
url(r'^oauth2/', include('provider.oauth2.urls', namespace='oauth2')),
2013-03-01 05:09:52 +04:00
2013-03-09 04:31:19 +04:00
Note that the `namespace='oauth2'` argument is required.
2013-03-01 05:09:52 +04:00
2013-03-09 04:31:19 +04:00
Finally, sync your database.
2013-03-01 05:09:52 +04:00
2013-03-09 04:31:19 +04:00
python manage.py syncdb
python manage.py migrate
2013-03-01 05:09:52 +04:00
2013-03-09 04:31:19 +04:00
---
2013-04-11 09:00:40 +04:00
**Note:** If you use `OAuth2Authentication` in production you must ensure that your API is only available over `https`.
2013-03-01 05:09:52 +04:00
2013-03-09 04:31:19 +04:00
---
2013-03-01 05:09:52 +04:00
2013-03-07 21:43:13 +04:00
#### Getting started with django-oauth2-provider
2013-03-01 05:09:52 +04:00
2013-05-28 19:13:12 +04:00
The `OAuth2Authentication` class only provides token verification for requests. It doesn't provide authorization flow for your clients.
2013-03-09 04:31:19 +04:00
2013-05-28 19:13:12 +04:00
The OAuth 2 authorization flow is taken care by the [django-oauth2-provider][django-oauth2-provider] dependency. A walkthrough is given here, but for more details you should refer to [the documentation][django-oauth2-provider-docs].
2013-03-09 04:31:19 +04:00
To get started:
##### 1. Create a client
You can create a client, either through the shell, or by using the Django admin.
2013-03-01 05:09:52 +04:00
2013-05-28 19:13:12 +04:00
Go to the admin panel and create a new `Provider.Client` entry. It will create the `client_id` and `client_secret` properties for you.
2013-03-01 05:09:52 +04:00
2013-03-09 04:31:19 +04:00
##### 2. Request an access token
2013-03-01 05:09:52 +04:00
2013-03-09 04:31:19 +04:00
To request an access token, submit a `POST` request to the url `/oauth2/access_token` with the following fields:
2013-03-01 05:09:52 +04:00
* `client_id` the client id you've just configured at the previous step.
* `client_secret` again configured at the previous step.
* `username` the username with which you want to log in.
* `password` well, that speaks for itself.
2013-03-09 04:31:19 +04:00
You can use the command line to test that your local configuration is working:
2013-03-01 05:09:52 +04:00
2013-03-09 04:31:19 +04:00
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/
2013-03-01 05:09:52 +04:00
2013-03-09 04:31:19 +04:00
You should get a response that looks something like this:
2013-03-01 05:09:52 +04:00
{"access_token": "<your-access-token>", "scope": "read", "expires_in": 86399, "refresh_token": "<your-refresh-token>"}
2013-03-09 04:31:19 +04:00
##### 3. Access the API
2013-03-01 05:09:52 +04:00
2013-03-09 04:31:19 +04:00
The only thing needed to make the `OAuth2Authentication` class work is to insert the `access_token` you've received in the `Authorization` request header.
2013-03-01 05:09:52 +04:00
2013-03-07 21:43:13 +04:00
The command line to test the authentication looks like:
curl -H "Authorization: Bearer <your-access-token>" http://localhost:8000/api/
2013-03-07 23:49:36 +04:00
---
2012-10-15 16:27:50 +04:00
# Custom authentication
2012-09-05 16:03:55 +04:00
2012-10-17 17:59:53 +04:00
To implement a custom authentication scheme, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise.
In some circumstances instead of returning `None`, you may want to raise an `AuthenticationFailed` exception from the `.authenticate()` method.
2012-10-17 17:59:53 +04:00
Typically the approach you should take is:
* If authentication is not attempted, return `None`. Any other authentication schemes also in use will still be checked.
* If authentication is attempted but fails, raise a `AuthenticationFailed` exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.
2012-10-17 17:59:53 +04:00
2013-01-28 16:05:52 +04:00
You *may* also override the `.authenticate_header(self, request)` method. If implemented, it should return a string that will be used as the value of the `WWW-Authenticate` header in a `HTTP 401 Unauthorized` response.
2012-10-17 17:59:53 +04:00
2013-01-28 16:05:52 +04:00
If the `.authenticate_header()` method is not overridden, the authentication scheme will return `HTTP 403 Forbidden` responses when an unauthenticated request is denied access.
2012-09-05 16:03:55 +04:00
## Example
The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X_USERNAME'.
class ExampleAuthentication(authentication.BaseAuthentication):
2013-02-24 02:32:47 +04:00
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 authenticate.AuthenticationFailed('No such user')
return (user, None)
---
# Third party packages
The following third party packages are also available.
## Digest Authentication
HTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. [Juan Riaza][juanriaza] maintains the [djangorestframework-digestauth][djangorestframework-digestauth] package which provides HTTP digest authentication support for REST framework.
2012-09-05 16:03:55 +04:00
2012-09-12 13:12:13 +04:00
[cite]: http://jacobian.org/writing/rest-worst-practices/
2012-10-17 17:59:53 +04:00
[http401]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
[http403]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4
2012-09-05 16:03:55 +04:00
[basicauth]: http://tools.ietf.org/html/rfc2617
[oauth]: http://oauth.net/2/
[permission]: permissions.md
2012-09-05 23:10:06 +04:00
[throttling]: throttling.md
[csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
[mod_wsgi_official]: http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPassAuthorization
2013-03-05 21:39:34 +04:00
[custom-user-model]: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#specifying-a-custom-user-model
2013-03-05 21:42:31 +04:00
[south-dependencies]: http://south.readthedocs.org/en/latest/dependencies.html
[juanriaza]: https://github.com/juanriaza
[djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth
2013-03-07 21:43:13 +04:00
[oauth-1.0a]: http://oauth.net/core/1.0a
2013-03-07 23:49:36 +04:00
[django-oauth-plus]: http://code.larlet.fr/django-oauth-plus
2013-03-01 15:02:03 +04:00
[django-oauth2-provider]: https://github.com/caffeinehit/django-oauth2-provider
2013-03-09 04:31:19 +04:00
[django-oauth2-provider-docs]: https://django-oauth2-provider.readthedocs.org/en/latest/
2013-03-01 05:09:52 +04:00
[rfc6749]: http://tools.ietf.org/html/rfc6749