Generating and using tokens

Now, we will launch our default Python interactive shell in our virtual environment and make all the Django project modules available to write code that will generate a token for an existing user. We will do this to understand how the token generation works.

Run the following command to launch the interactive shell. Make sure you are within the restful01 folder in the terminal, Command Prompt, or Windows Powershell:

   python manage.py shell

You will notice that a line that says (InteractiveConsole) is displayed after the usual lines that introduce your default Python interactive shell. Enter the following code in the Python interactive shell to import all the things we will need to retrieve a User instance and generate a new token. The code file for the sample is included in the hillar_django_restful_08_02 folder, in the restful01/tokens_test_01.py file.

from rest_framework.authtoken.models import Token 
from django.contrib.auth.models import User 

Enter the following code to retrieve an instance of the User model whose username matches "user01" and create a new Token instance related to this user. The last line prints the value for the key attribute for the generated Token instance saved in the token variable. Replace user01 in the next lines with the name you configured for this user. The code file for the sample is included in the hillar_django_restful_08_02 folder, in the restful01/tokens_test_01.py file:

# Replace user01 with the name you configured for this user 
user = User.objects.get(username="user01") 
token = Token.objects.create(user=user) 
print(token.key) 

The following line shows a sample output from the previous code with the string value for token.key. Copy the output generated when running the code because we will use this token to authenticate requests. Notice that the token generated in your system will be different:

    ebebe08f5d7fe5997f9ed1761923ec5d3e461dc3

Finally, enter the following command to quit the interactive console:

    quit()

Now, we have a token for the Django user named user01.

Now, we can launch Django's development server to compose and send HTTP requests to retrieve pilots to understand how the configured token authentication class combined with the permission policies work. Execute any of the following two commands based on your needs to access the API in other devices or computers connected to your LAN. Remember that we analyzed the difference between them in Chapter 3, Creating API Views, in the Launching Django's development server section:

    python manage.py runserver
    python manage.py runserver 0.0.0.0:8000

After we run any of the previous commands, the development server will start listening at port 8000.

We will compose and send an HTTP GET request without authentication credentials to try to retrieve the first page of the pilots collection:

    http :8000/pilots/

The following is the equivalent curl command:

    curl -iX GET localhost:8000/pilots/

We will receive an HTTP 401 Unauthorized status code in the response header and a detail message indicating that we didn't provide authentication credentials in the JSON body. In addition, the value for the WWW-Authenticate header specifies the authentication method that must be applied to access the resource collection: Token. The following lines show a sample response:

HTTP/1.0 401 Unauthorized
Allow: GET, POST, HEAD, OPTIONS
Content-Length: 58
Content-Type: application/json
Date: Sat, 18 Nov 2017 02:28:31 GMT
Server: WSGIServer/0.2 CPython/3.6.2
Vary: Accept
WWW-Authenticate: Token
X-Frame-Options: SAMEORIGIN

{
"detail": "Authentication credentials were not provided."
}

After the changes we made, if we want to retrieve the collection of pilots, that is, to make an HTTP GET request to /pilots/, we need to provide authentication credentials by using the token-based authentication. Now, we will compose and send an HTTP request to retrieve the collection of pilots with authentication credentials, that is, with the token. Remember to replace PASTE-TOKEN-HERE with the previously generated token:

    http :8000/pilots/ "Authorization: Token PASTE-TOKEN-HERE"

The following is the equivalent curl command:

  curl -iX GET http://localhost:8000/pilots/ -H "Authorization: Token 
PASTE-TOKEN-HERE"

As a result of the request, we will receive an HTTP 200 OK status code in the response header and the first page of the pilots collection serialized to JSON in the response body. The following screenshot shows the first lines of a sample response for the request with the appropriate token:

The token-based authentication provided with the Django REST framework is very simple and it requires customization to make it production ready. Tokens never expire and there is no setting to specify the default expiration time for a token.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset