frlinw
frlinw

Reputation: 562

Django rest framework, JWT and request.session

I use Django rest framework with JWT for authentication and everything works perfectly BUT... I need to save an information about the user in a session var at login and I really don't know where I can do the request.session['mydata'] = plop

I tried :

def jwt_response_payload_handler(token, user=None, request=None):
  serializedUser = UserSerializer(user).data
  request.session['mydata'] = serializedUser.mydata
  return {
    'token': token,
    'user': serializedUser
  }

But it doesn't work...

Any idea ?

Upvotes: 6

Views: 5456

Answers (2)

shanemgrey
shanemgrey

Reputation: 2378

Try this

def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'user': UserSerializer(
            user,
            context={
                'request': request
            },
        ).data
    }

Whatever fields you add to your UserSerializer will be included in the response along with the token.

You can then use that to store the information in localstorage along with the token so that it's available to your SPA without having to make a separate call each time.

The only difference from the docs is the addition of context={'request': request}, which is probably a result of a change in the DRF since the JWT docs were written.

Upvotes: 2

Kevin Brown-Silva
Kevin Brown-Silva

Reputation: 41699

request.session is managed through Django's session framework which requires the use of session cookies and is what powers SessionAuthentication.

JWT is completely separate from session authentication, and does not provide a way to store arbitrary data on the token.

Upvotes: 5

Related Questions