diff options
| author | Michael Elovskikh | 2013-01-28 16:26:16 +0600 | 
|---|---|---|
| committer | Michael Elovskikh | 2013-01-28 16:26:16 +0600 | 
| commit | 499d6424aee5b71b8e6b2500bf14fa85321bfc26 (patch) | |
| tree | 34f575fb078377208ded5251aea050668355d82a /docs/api-guide/authentication.md | |
| parent | 180c94dc44a9cc5b882364a58b0b12a8ab430c22 (diff) | |
| parent | 3bcd38b7d0ddaa2c051ad230cb0d749f9737fd82 (diff) | |
| download | django-rest-framework-499d6424aee5b71b8e6b2500bf14fa85321bfc26.tar.bz2 | |
Merge branch 'upstream_master' into docs_patch_method
Conflicts:
	docs/api-guide/authentication.md
Diffstat (limited to 'docs/api-guide/authentication.md')
| -rw-r--r-- | docs/api-guide/authentication.md | 97 | 
1 files changed, 86 insertions, 11 deletions
| diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 2d34d788..da494746 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -8,7 +8,7 @@  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.      class ExampleView(APIView):          authentication_classes = (SessionAuthentication, BasicAuthentication) @@ -60,24 +68,52 @@ 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. + +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 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. @@ -93,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) @@ -127,22 +168,56 @@ 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`, `PATCH`, `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. + +## 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): +        def has_permission(self, request, view, obj=None): +            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) +                  [cite]: http://jacobian.org/writing/rest-worst-practices/ +[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  [basicauth]: http://tools.ietf.org/html/rfc2617  [oauth]: http://oauth.net/2/  [permission]: permissions.md  [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 | 
