Issue
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,
- Where are these tokens stored on the user's side?
- How will the user be able to add the
access
token to requests that are protected? (they can't copy-paste like me) - How will they use the
refresh
token to renew theaccess
token
I would appreciate if someone cleared this up for me.
Solution
So, if you're talking about the client side, where users will be using your application using the front-end:
The tokens can be stored on local storage of your browser
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.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));
Answered By - Shahriar Rahman Zahin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.