Django rest framework, JWT and request.session

我怕爱的太早我们不能终老 提交于 2019-12-10 09:45:45

问题


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 ?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/30546704/django-rest-framework-jwt-and-request-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!