davidcr01 / WordlePlus

Repository to store all the documentation, files and structure of my Final Degree Project (TFG in Spanish). The main goal is to develop, as full-stack web developer, a remodel of the Wordle game, including more features and functionalities using Ionic, Django REST Api and PostgreSQL.
1 stars 0 forks source link

Improve Token generation (S2) #15

Closed davidcr01 closed 1 year ago

davidcr01 commented 1 year ago

Description

It is necessary to improve the token generation for the user. A good idea to improve the security of the application is to set expiration dates to the token. An undefined token is a problem of security if it's intercepted by any attacker.

Generating temporal tokens would be a good security improvement.

davidcr01 commented 1 year ago

Update Report

Development

A new middleware has been developed, TokenExpirationMiddleware stored in a new file token_expire.py, inside the application folder. In DRF, middlewares are components which are executed during the processing of an HTTP request before using the views.

class TokenExpirationMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        auth_header = request.META.get('HTTP_AUTHORIZATION')
        if auth_header:
            _, token_key = auth_header.split()
            token = Token.objects.filter(key=token_key).first()
            if token and token.created < timezone.now() - timedelta(seconds=settings.TOKEN_EXPIRED_AFTER_SECONDS):
                token.delete()

                response_data = {
                    'message': 'Token has expired.'
                }
                response = JsonResponse(response_data, status=status.HTTP_401_UNAUTHORIZED)
                return response

        response = self.get_response(request)
        return response

This code snippet gets the token of the request and check if the token is expired by doing a substraction of timestamps. If the token is expired, then is removed.

To use this middleware, modify the settings.py file:

MIDDLEWARE = [
    ...
    'djapi.token_expire.TokenExpirationMiddleware'

The TOKEN_EXPIRED_AFTER_SECONDS variable is also defined in the settings.py file.

Testing

To test the development:

Create a token, either with the API or the Admin site: image

Wait the expire time and make an API call again and check if the token has expired: image

Check if the token exists: image

The token is no longer available. The platform will need to re-generate the token by using the api-token-auth URL.