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

后端 未结 10 1319
庸人自扰
庸人自扰 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:03

    If anyone wants to expire the token after certain time of inactivity, below answer would help. I am tweaking one of the answers given here. I have added comments to the code I added

    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(minutes=15):  # TOKEN WILL EXPIRE AFTER 15 MINUTES OF INACTIVITY
                token.delete() # ADDED THIS LINE SO THAT EXPIRED TOKEN IS DELETED
                raise exceptions.AuthenticationFailed('Token has expired')
            else: 
                token.created = utc_now #THIS WILL SET THE token.created TO CURRENT TIME WITH EVERY REQUEST
                token.save() #SAVE THE TOKEN
    
            return token.user, token
    

提交回复
热议问题