Reputation: 23
I use SimpleJWT and RestFramework for Authentication. The Tokens are stored in the cookies after login is finished and request is send to the login api which is in React.
class CustomTokenObtainPairView(TokenObtainPairView):
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
try:
serializer.is_valid(raise_exception=True)
except TokenError as e:
raise InvalidToken(e.args[0])
# set access token in browser with Httponly cookie.
res = Response(serializer.validated_data, status=status.HTTP_200_OK)
access_token = serializer.validated_data['access']
res.set_cookie("access_token", access_token, max_age=settings.SIMPLE_JWT.get('ACCESS_TOKEN_LIFETIME').total_seconds(),samesite='Lax',secure=False, httponly=True)
return res
Cookies accessed from Django:
print(request.COOKIES)
returns:
{'userVisitedBefore': 'true', 'tabstyle': 'html-tab', 'csrftoken': 'NECdxoDLb6fszteb8dB11ELh9l2keYUuHM13AaRAxHUHX45GJ9URloJnia9GrqCS', 'sessionid': 'jjafw09sok8wa05756ntjNr6nwxhg6q0', 'access_token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1niJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjM0NTY1ODk0LCJpYXQiOjE2MzQ1NjQ5OTQsImp0aSI6Ijc1ZGY0Njc4MzY1ZDRlNjc5NDM1NTRlMTgzMTU5Nzc1IiwidXNlcl9pZCI6MX0.2Ew92rRIRvoxylpgRu4uGnRGdOuoPV7NSgmGxzS6bnw'}
Cookies accessed from React:
const cookies = new Cookies();
console.log(cookies.getAll([]))
returns this without the access_token and session id:
{userVisitedBefore: 'true', tabstyle: 'html-tab', csrftoken: 'NECdxoDLb6fszteb8dB11ELh9l2keYUuhM13AaRAxHUHX45GJ9URloJnia9GrqCS'}
Upvotes: 1
Views: 1352
Reputation: 23
For anyone interested: My "Solution" was to save the Token in the Cookies via universal-cookie which were then accessable from both Django Views and the React Frontend. Also instead of saving them via a CustomTokenObtainView, I saved them directly in the React Login Component likes this:
axiosInstance
.post(`api/token/`, {
email: formData.email,
password: formData.password,
})
.then((res) => {
cookies.set('access_token', localStorage.getItem('access_token'), { path: '/'});
axiosInstance.defaults.headers['Authorization'] = 'JWT ' + localStorage.getItem('access_token');
history.push("");
location.reload();
}).catch(err => console.log(err));
Upvotes: 1