How does refreshing of jwt token work in django REST angular

1.6k views Asked by At

I am using this

http://getblimp.github.io/django-rest-framework-jwt/#refresh-token

I am confused how to make it work. I have done all settings as said. Now how to make it work.

Currently i have code to get first token when user submits login and i save that token in cookie store. Then my request use that token for all requests. I have seen that token sometimes expries and i don't want that. so thats why i am using this

$http
    .post('/api-token-auth/', logData)
    .then(function (response) {
        // assumes if ok, response is an object with some data, if not, a string with error
        // customize according to your api
        if (!response.data.token) {
            _vm.authMsg = 'Incorrect credentials.';
            deferred.reject('Incorrect credentials.');
        } else {
            $cookieStore.put('djangotoken', response.data.token);
            $http.defaults.headers.common.Authorization = 'JWT ' + response.data.token;
            $http.get('/api/account/restricted/').then(function (response) {
                authService.loginConfirmed();
                $cookieStore.put('currentUser', response.data);
                $rootScope.$broadcast('user:login');
            });
        }
        deferred.resolve(response.data);
        }, function (x) {
            _vm.authMsg = 'Server Request Error';
            deferred.reject('Server Request Error');
        });

This is how i am using that token in every request

   $http.defaults.headers.common['Authorization'] = 'JWT ' + $cookieStore.get('djangotoken');

Now what do need to do to make refresh token work. I mean does user has to manually refresh the token or system will automatically do it. and at what point do i need to visit this url

url(r'^api-token-refresh/', 'rest_framework_jwt.views.refresh_jwt_token'),
1

There are 1 answers

6
Peter Brittain On BEST ANSWER

The documentation so that you referenced was quite explicit. Pass in an existing token to the refresh endpoint as follows [snipped description]:

$ curl -X POST -H "Content-Type: application/json" -d '{"token":"<EXISTING_TOKEN>"}' http://localhost:8000/api-token-refresh/

You have to invoke the refresh URL to make it work. That means either your client needs to monitor when it needs to refresh the token and so invoke the URL, or you could put some logic in the server to invoke this URL for a subset of requests where you expect the user to take a long time to traverse them all (e.g. filling in a long multi-page form).

If you decide to go for the latter you might find this useful.