使用django rest框架jwt将信息添加到JWT令牌主体 [英] Adding information to JWT token body using django rest framework jwt

查看:163
本文介绍了使用django rest框架jwt将信息添加到JWT令牌主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用django rest框架和djangorestframework-jwt包创建用于授权的JWT令牌。

Im using django rest framework and the djangorestframework-jwt package to creat JWT tokens for authorization.

在前端,我可以解码令牌并获取用户名,电子邮件和user_id。但是,我想检索一些额外的信息。例如,如果我可以得到 kind (这是我们的授权模型(用户模型)上的一个字段),那将非常方便。

On the frontend I can decode the token and get the username, email and user_id. However I would like to retrieve some extra information. For example it would be very convenient if I could get kind which is a field on our authorization model (user model).

我当然可以提出一个单独的请求,以通过常规APIView获取用户信息。但是我想知道是否可以在JWT主体中添加一些额外的参数?

I can ofcourse make a separate request to get the user info via a regular APIView. But I'm wondering if it's possible to add some extra params in the JWT body?

推荐答案

如本 github问题,我通过将从DRF-JWT获得JSONWebToken 类:

from rest_framework_jwt import views as jwt_views
from .serializers import UserSerializer 

class UserLoginViewJWT(jwt_views.ObtainJSONWebToken):
    user_serializer_class = UserSerializer

    def post(self, request, *args, **kwargs):
        response =  super().post(request, *args, **kwargs)

        if response.status_code == status.HTTP_200_OK:
            user = get_user_model().objects.get(email=request.data[get_user_model().USERNAME_FIELD])
            serialized_user = self.user_serializer_class(user)
            response.data.update(serialized_user.data)
        return response

注意:上面的代码可能丢失某些进口商品

Note: the code above is probably missing some imports

@jpadilla的回复还指定

A reply from @jpadilla also specified that


使用JWT_RESPONSE_PAYLOAD_HANDLER设置执行此操作。
http://getblimp.github.io/django-rest -framework-jwt /#jwt_response_payload_handler

这篇关于使用django rest框架jwt将信息添加到JWT令牌主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆