Django Rest Framework JWT: How to change the token expiration time when logged in

前端 未结 3 1135
甜味超标
甜味超标 2020-12-17 01:53

I\'m using Django REST framework JWT Auth for session creation and permissions, the only problem is: when I log in and after the token expires I can\'t continue doing the op

3条回答
  •  渐次进展
    2020-12-17 02:20

    I've had same problem in angularjs and I've solved it by writing a custom interceptor service for my authentication headers.

    Here's my code:

    function($http, $q, store, jwtHelper) {
        let cache = {};
        return {
          getHeader() {
            if (cache.access_token && !jwtHelper.isTokenExpired(cache.access_token)) {
    
              return $q.when({ 'Authorization': 'Token ' + cache.access_token });
    
            } else {
              cache.access_token = store.get('token');
              if (cache.access_token && !jwtHelper.isTokenExpired(cache.access_token)) {
    
                return $q.when({ 'Authorization': 'Token ' + cache.access_token });
    
              } else {
                return $http.post(localhost + 'api-token-refresh/',{'token': cache.access_token})
                .then(response => {
                  store.set('token', response.data.token);
                  cache.access_token = response.data.token;
                  console.log('access_token', cache.access_token);
                  return {'Authorization': 'Token ' + cache.access_token};
    
                },
                err => {
                  console.log('Error Refreshing token ',err);
                }
              );
              }
            }
          }
        };
    
    
      }
    

    Here, on every request I've had to send, the function checks whether the token is expired or not. If its expired, then a post request is sent to the "api-token-refresh" in order to retrieve the new refreshed token, prior to the current request. If not, the nothing's changed.

    But, you have to explicitly call the function getHeader() prior to the request to avoid circular dependency problem.

    This chain of requests can be written into a function like this,

    someResource() {
    return someService.getHeader().then(authHeader => { 
    return $http.get(someUrl, {headers: authHeader}); 
    

    }); }

提交回复
热议问题