Token Authentication for RESTful API: should the token be periodically changed?

后端 未结 10 1296
庸人自扰
庸人自扰 2020-12-02 03:20

I\'m building a RESTful API with Django and django-rest-framework.

As authentication mechanism we have chosen \"Token Authentication\" and I have already implemented

10条回答
  •  既然无缘
    2020-12-02 04:05

    just to keep adding to @odedfos answer, I think there have been some changes to the syntax so the code of ExpiringTokenAuthentication needs some adjusting:

    from rest_framework.authentication import TokenAuthentication
    from datetime import timedelta
    from datetime import datetime
    import datetime as dtime
    import pytz
    
    class ExpiringTokenAuthentication(TokenAuthentication):
    
        def authenticate_credentials(self, key):
            model = self.get_model()
            try:
                token = model.objects.get(key=key)
            except model.DoesNotExist:
                raise exceptions.AuthenticationFailed('Invalid token')
    
            if not token.user.is_active:
                raise exceptions.AuthenticationFailed('User inactive or deleted')
    
            # This is required for the time comparison
            utc_now = datetime.now(dtime.timezone.utc)
            utc_now = utc_now.replace(tzinfo=pytz.utc)
    
            if token.created < utc_now - timedelta(hours=24):
                raise exceptions.AuthenticationFailed('Token has expired')
    
            return token.user, token
    

    Also, don't forget to add it to DEFAULT_AUTHENTICATION_CLASSES instead of rest_framework.authentication.TokenAuthentication

提交回复
热议问题