How do I get the JWT tokens from user in Django RestFramework

Question:

I have a DRF project using Simple-JWT for authentication. When a user logs in, they get a response containing the access and refresh tokens in the serializer.data. However:

When testing on the Apis I can manually copy and paste these tokens and add them to headers when making requests. However in production,

  1. Where are these tokens stored on the user’s side?
  2. How will the user be able to add the access token to requests that are protected? (they can’t copy-paste like me)
  3. How will they use the refresh token to renew the access token.
Asked By: sajeyks mwangi

||

Answers:

So, if you’re talking about the client side, where users will be using your application using the front-end:

  1. The tokens can be stored on local storage of your browser

  2. All the authenticated URL requests must contain a bearer token where you will add the access_token which your API will return after authentication and is currently saved in your local storage.

  3. for getting refresh token, add a URL like below where you will send a post request:

     from rest_framework_simplejwt.views import (
         TokenObtainPairView,
         TokenRefreshView,
         TokenVerifyView,
     )
     urlpatterns = [
     ...
    
         path(
             'token/refresh/',
             TokenRefreshView.as_view(),
             name='token_refresh',
         ),
     ...
     ]
    

Finally someone can use this code on JS side for saving or retrieving tokens from localstorage:

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('retrievedObject: ', JSON.parse(retrievedObject));