* Support proper 401 Unauthorized responses where appropriate, instead of always using 403 Forbidden.
* Support json encoding of timedelta objects.
*`format_suffix_patterns()` now supports `include` style URL patterns.
* Bugfix: Fix issues with custom pagination serializers.
* Bugfix: Nested serializers now accept `source='*'` argument.
* Bugfix: Return proper validation errors when incorrect types supplied for relational fields.
* Bugfix: Support nullable FKs with `SlugRelatedField`.
* Bugfix: Don't call custom validation methods if the field has an error.
**Note**: If the primary authentication class is `TokenAuthentication` or `BasicAuthentication`, a view will now correctly return 401 responses to unauthenticated access, with an appropriate `WWW-Authenticate` header, instead of 403 responses.
### 2.1.16
**Date**: 14th Jan 2013
...
...
@@ -131,20 +146,20 @@ This change will not affect user code, so long as it's following the recommended
* Bugfix: Fix exception in browseable API on DELETE.
* Bugfix: Fix issue where pk was was being set to a string if set by URL kwarg.
## 2.1.11
### 2.1.11
**Date**: 17th Dec 2012
* Bugfix: Fix issue with M2M fields in browseable API.
## 2.1.10
### 2.1.10
**Date**: 17th Dec 2012
* Bugfix: Ensure read-only fields don't have model validation applied.
* Bugfix: Fix hyperlinked fields in paginated results.
## 2.1.9
### 2.1.9
**Date**: 11th Dec 2012
...
...
@@ -152,14 +167,14 @@ This change will not affect user code, so long as it's following the recommended
* Bugfix: Fix `Meta.fields` only working as tuple not as list.
* Bugfix: Edge case if unnecessarily specifying `required=False` on read only field.
## 2.1.8
### 2.1.8
**Date**: 8th Dec 2012
* Fix for creating nullable Foreign Keys with `''` as well as `None`.
* Added `null=<bool>` related field option.
## 2.1.7
### 2.1.7
**Date**: 7th Dec 2012
...
...
@@ -171,19 +186,19 @@ This change will not affect user code, so long as it's following the recommended
* Make `Request.user` settable.
* Bugfix: Fix `RegexField` to work with `BrowsableAPIRenderer`
## 2.1.6
### 2.1.6
**Date**: 23rd Nov 2012
* Bugfix: Unfix DjangoModelPermissions. (I am a doofus.)
## 2.1.5
### 2.1.5
**Date**: 23rd Nov 2012
* Bugfix: Fix DjangoModelPermissions.
## 2.1.4
### 2.1.4
**Date**: 22nd Nov 2012
...
...
@@ -194,7 +209,7 @@ This change will not affect user code, so long as it's following the recommended
* Added `obtain_token_view` to get tokens when using `TokenAuthentication`.
* Bugfix: Django 1.5 configurable user support for `TokenAuthentication`.
## 2.1.3
### 2.1.3
**Date**: 16th Nov 2012
...
...
@@ -205,14 +220,14 @@ This change will not affect user code, so long as it's following the recommended
* 201 Responses now return a 'Location' header.
* Bugfix: Serializer fields now respect `max_length`.
## 2.1.2
### 2.1.2
**Date**: 9th Nov 2012
***Filtering support.**
* Bugfix: Support creation of objects with reverse M2M relations.
## 2.1.1
### 2.1.1
**Date**: 7th Nov 2012
...
...
@@ -222,7 +237,7 @@ This change will not affect user code, so long as it's following the recommended
* Bugfix: Make textareas same width as other fields in browsable API.
* Private API change: `.get_serializer` now uses same `instance` and `data` ordering as serializer initialization.
## 2.1.0
### 2.1.0
**Date**: 5th Nov 2012
...
...
@@ -235,13 +250,13 @@ This change will not affect user code, so long as it's following the recommended
* Minor field improvements. (Don't stringify dicts, more robust many-pk fields.)
* Bugfixes (Support choice field in Browseable API)
## 2.0.2
### 2.0.2
**Date**: 2nd Nov 2012
* Fix issues with pk related fields in the browsable API.
## 2.0.1
### 2.0.1
**Date**: 1st Nov 2012
...
...
@@ -249,12 +264,12 @@ This change will not affect user code, so long as it's following the recommended
* Added SlugRelatedField and ManySlugRelatedField.
* If PUT creates an instance return '201 Created', instead of '200 OK'.
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 a number of authentication policies out of the box, and also allows you to implement custom policies.
REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.
Authentication will run the first time either the `request.user` or `request.auth` properties are accessed, and determines how those properties are initialized.
...
...
@@ -16,17 +16,25 @@ The `request.user` property will typically be set to an instance of the `contrib
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 setup the permission polices for your API please see the [permissions documentation][permission].
---
## How authentication is determined
The authentication policy is 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.
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 policy
## Setting the authentication scheme
The default authentication policy may be set globally, using the `DEFAULT_AUTHENTICATION_CLASSES` setting. For example.
The default authentication schemes may be set globally, using the `DEFAULT_AUTHENTICATION` setting. For example.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
...
...
@@ -35,7 +43,7 @@ The default authentication policy may be set globally, using the `DEFAULT_AUTHEN
)
}
You can also set the authentication policy on a per-view basis, using the `APIView` class based views.
You can also set the authentication scheme on a per-view basis, using the `APIView` class based views.
@@ -60,6 +68,19 @@ Or, if you're using the `@api_view` decorator with function based views.
}
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][http401]
*[HTTP 403 Permission Denied][http403]
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][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.
...
...
@@ -69,24 +90,30 @@ If you are deploying to Apache, and using any non-session based authentication,
# this can go in either server config, virtual host, directory or .htaccess
WSGIPassAuthorization On
---
# API Reference
## BasicAuthentication
This policy uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. Basic authentication is generally only appropriate for testing.
This authentication scheme uses [HTTP Basic Authentication][basicauth], 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` only. 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 policy uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.
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`policy, include `rest_framework.authtoken` in your `INSTALLED_APPS` setting.
To use the `TokenAuthentication`scheme, include `rest_framework.authtoken` in your `INSTALLED_APPS` setting.
You'll also need to create tokens for your users.
...
...
@@ -102,10 +129,15 @@ For clients to authenticate, the token key should be included in the `Authorizat
If successfully authenticated, `TokenAuthentication` provides the following credentials.
*`request.user` will be a Django `User` instance.
*`request.auth` will be a `rest_framework.tokenauth.models.BasicToken` instance.
*`request.auth` will be a `rest_framework.authtoken.models.BasicToken` 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
**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https` only.
=======
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)
...
...
@@ -136,20 +168,35 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
## SessionAuthentication
This policy 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.
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.
If successfully authenticated, `SessionAuthentication` 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 403 Forbidden` response.
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`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
# Custom authentication
To implement a custom authentication policy, 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.
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.
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, without checking any other authentication schemes.
You *may* also override the `.authentication_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.
If the `.authentication_header()` method is not overridden, the authentication scheme will return `HTTP 403 Forbidden` responses when an unauthenticated request is denied access.
@@ -53,11 +53,27 @@ Raised if the request contains malformed data when accessing `request.DATA` or `
By default this exception results in a response with the HTTP status code "400 Bad Request".
## AuthenticationFailed
**Signature:**`AuthenticationFailed(detail=None)`
Raised when an incoming request includes incorrect authentication.
By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.
## NotAuthenticated
**Signature:**`NotAuthenticated(detail=None)`
Raised when an unauthenticated request fails the permission checks.
By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.
## PermissionDenied
**Signature:**`PermissionDenied(detail=None)`
Raised when an incoming request fails the permission checks.
Raised when an authenticated request fails the permission checks.
By default this exception results in a response with the HTTP status code "403 Forbidden".
...
...
@@ -86,3 +102,4 @@ Raised when an incoming request fails the throttling checks.
By default this exception results in a response with the HTTP status code "429 Too Many Requests".
@@ -114,8 +114,8 @@ You can also override the name used for the object list field, by setting the `r
For example, to nest a pair of links labelled 'prev' and 'next', and set the name for the results field to 'objects', you might use something like this.
class LinksSerializer(serializers.Serializer):
next = pagination.NextURLField(source='*')
prev = pagination.PreviousURLField(source='*')
next = pagination.NextPageField(source='*')
prev = pagination.PreviousPageField(source='*')
class CustomPaginationSerializer(pagination.BasePaginationSerializer):
links = LinksSerializer(source='*') # Takes the page object as the source
@@ -136,6 +142,11 @@ For support please see the [REST framework discussion group][group], try the `#
[Paid support is available][paid-support] from [DabApps][dabapps], and can include work on REST framework core, or support with building your REST framework API. Please [contact DabApps][contact-dabapps] if you'd like to discuss commercial support options.
For updates on REST framework development, you may also want to follow [the author][twitter] on Twitter.
@@ -16,11 +16,20 @@ Major version numbers (x.0.0) are reserved for project milestones. No major poi
## 2.1.x series
### Master
### 2.1.17
**Date**: 26th Jan 2013
* Support proper 401 Unauthorized responses where appropriate, instead of always using 403 Forbidden.
* Support json encoding of timedelta objects.
*`format_suffix_patterns()` now supports `include` style URL patterns.
* Bugfix: Fix issues with custom pagination serializers.
* Bugfix: Nested serializers now accept `source='*'` argument.
* Bugfix: Return proper validation errors when incorrect types supplied for relational fields.
* Bugfix: Support nullable FKs with `SlugRelatedField`.
* Bugfix: Don't call custom validation methods if the field has an error.
**Note**: If the primary authentication class is `TokenAuthentication` or `BasicAuthentication`, a view will now correctly return 401 responses to unauthenticated access, with an appropriate `WWW-Authenticate` header, instead of 403 responses.
@@ -109,7 +109,7 @@ The first thing we need to get started on our Web API is provide a way of serial
from django.forms import widgets
from rest_framework import serializers
from snippets import models
from snippets.models import Snippet
class SnippetSerializer(serializers.Serializer):
...
...
@@ -138,7 +138,7 @@ The first thing we need to get started on our Web API is provide a way of serial
return instance
# Create new instance
return models.Snippet(**attrs)
return Snippet(**attrs)
The first part of serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data.
@@ -164,7 +166,8 @@ In the snippets app, create a new file, `permissions.py`
if obj is None:
return True
# Read permissions are allowed to any request
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
...
...
@@ -188,4 +191,4 @@ We've now got a fairly fine-grained set of permissions on our Web API, and end p
In [part 5][tut-5] of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our hightlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.