获取用户角色并将其添加到jwt有效负载

时间:2018-02-15 08:41:00

标签: python django django-rest-framework

我有用户登录Serializer如下所示我想在用户通过身份验证时将用户角色添加到我的jwt有效负载中如何访问用户信息,例如" is_stuff"我的验证功能中的字段?用户对象包含class UserLoginSerializer(ModelSerializer): token = CharField(allow_blank=True, read_only=True) username = CharField(required=False, allow_blank=True) email = EmailField(label='email address', required=False, allow_blank=True) class Meta: model = User fields = [ 'username', 'email', 'password', 'token', 'is_staff', ] extra_kwargs = { "password": { "write_only": True } } def validate(self, data): user_obj = None email = data.get('email', None) username = data.get('username', None) password = data.get('password') if not email and not username: raise ValidationError("email or username is required!") if '@' in username: email = username user = User.objects.filter( Q(email=email) | Q(username=username) ).distinct() # user = user.exclude(email__isnull=True).exclude(email__iexact='') if user.exists() and user.count() == 1: user_obj = user.first() else: raise ValidationError("this username/email is not valid") if user_obj: if not user_obj.check_password(password): raise ValidationError("password is incorrect") payload = jwt_payload_handler(user_obj) payload["role"] = ??? data['token'] = jwt_encode_handler(payload) return data

class UserLoginApiView(APIView):
    permission_classes = [AllowAny]
    serializer_class = UserLoginSerializer

    def post(self, request, *args, **kwargs):
        data = request.data
        serializer = UserLoginSerializer(data=data)
        if serializer.is_valid(raise_exception=True):
            new_data = serializer.data
            return Response(new_data, status=HTTP_200_OK)

        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

查看:

{{1}}

1 个答案:

答案 0 :(得分:2)

如果您正在使用rest_framework_jwt,请定义:

JWT_AUTH = {
    ...
    'JWT_PAYLOAD_HANDLER': 'project.jwt.jwt_payload_handler',
    ...
}

您可以在此文件中定义自己的函数(或任何您称之为的函数)project.jwt

from django.conf import settings
from rest_framework_jwt import utils

def jwt_payload_handler(user):
    payload = utils.jwt_payload_handler(user)
    payload['is_staff'] = user.is_staff
    payload['is_superuser'] = user.is_superuser
    ....
    return payload