Package: django-tokenapi
django-tokenapiThis is a Django application which allows you to create simple APIs
that use token-based authentication. You can easily open up existing views
to the API by adding a single decorator.This is useful if you want to create applications on mobile devices which
connect to your Django website, but where only your clients are expected to
access the API.If instead you are looking to open up an API to the public, you are better off
going with a framework with OAuth support, of which there exist some really
goodimplementations.RequirementsDjango 1.9+Python 2.7 or 3+InstallationFirst obtaintokenapipackage and place it somewhere on yourPYTHONPATH, for example
in your project directory (where settings.py is).Alternatively, if you are
using some sort of virtual environment, likevirtualenv, you can perform a
regular installation or usepip:python setup.py install

# or ...

pip install django-tokenapiAddtokenapito yourINSTALLED_APPS.Ensure thatdjango.contrib.auth.backends.ModelBackendis in yourAUTHENTICATION_BACKENDS.Addtokenapi.backends.TokenBackendto yourAUTHENTICATION_BACKENDS.Includetokenapi.urlsin yoururls.py. It will look something like this:urlpatterns = [
    url(r'^token/', include('tokenapi.urls')),
]ConfigurationYou can change the number of days that a token is valid for by settingTOKEN_TIMEOUT_DAYSinsettings.py. The default is7.UsageObtaining a TokenYou can obtain a token for a specific user by sending a POST request with a
username and password parameter to theapi_token_newview.
Usingcurl, the request would look like:curl -d "username=jpulgarin&password=GGGGGG" http://www.yourdomain.com/token/new.jsonIf the request is successful, you will receive a JSON response like so:{"success": true, "token": "2uy-420a8efff7f882afc20d", "user": 1}An invalid username and password pair will produce a response like so:{"success": false, "errors": "Unable to log you in, please try again"}Note that if you User model has anis_activeflag, the authentication logic will not allow inactive users to obtain or use tokens.You should store theuserandtokenthat are returned on the client
accessing the API, as all subsequent calls will require that the request have
a valid token and user pair.Verifying a TokenYou can verify that a token matches a given user by sending a GET request
to theapi_tokenview, and sending the token and user as part of the URL.
Using curl it would look like:curl http://www.yourdomain.com/token/2uy-420a8efff7f882afc20d/1.jsonIf valid, you will receive the following JSON response:{"success": true}Writing API Compatible ViewsTo allow a view to be accessed through token-based auth, use thetokenapi.decorators.token_requireddecorator. There are also
JSON helper functions to make it easier to deal with JSON.
This is an example of an API compatible view:from tokenapi.decorators import token_required
from tokenapi.http import JsonResponse, JsonError, JsonResponseBadRequest, JsonResponseUnauthorized, JsonResponseForbidden, JsonResponseNotFound, JsonResponseNotAllowed, JsonResponseNotAcceptable


@token_required
def index(request):
    if request.method == 'POST':
        data = {
            'test1': 49,
            'test2': 'awesome',
        }
        return JsonResponse(data)
    else:
        return JsonError("Only POST is allowed")Using a TokenRequest ParametersThe client can access any API compatible view by sending a request to it,
and includinguserandtokenas request parameters (either GET or POST).
Accessing the example view above using curl might look like:curl -d "user=1&token=2uy-420a8efff7f882afc20d" http://www.yourdomain.com/index.jsonYou would receive the following response:{"success": true, "test1": 49, "test2": "awesome"}Basic authenticationAlternately, you can access any API compatible view by including the user and token in
the Authorization header according to thebasic access authenticationscheme. To construct the Authorization header:Combine user id and token into string "user:token"Encode resulting string using Base64Prepend "Basic " (including the trailing space) to the resulting Base64 encoded stringIf, in the same request, you provide credentials via both request parameters and the
Authorization header, the request parameters will be used for authentication.AcknowledgementsThe token generating code is fromdjango.contrib.auth.tokens, but modified so
that it does not hash on a user's last login.