Closed davidcr01 closed 1 year ago
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.
To test the development:
Create a token, either with the API or the Admin site:
Wait the expire time and make an API call again and check if the token has expired:
Check if the token exists:
The token is no longer available. The platform will need to re-generate the token by using the api-token-auth
URL.
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.