我正在尝试为django rest api身份验证编写自定义jwt登录视图。 但这是行不通的,我也不知道为什么。你能帮我修复这段代码或举一些例子吗?预先感谢。
我的序列化器:
class LoginSerializer(serializers.Serializer):
token = serializers.CharField(max_length=256)
username = serializers.CharField(max_length=128)
password = serializers.CharField(write_only=True,
required=True,
style={
'input_type': 'password',
'placeholder': 'password'
})
我的观点:
from .serializers import LoginSerializer
class UserLogin(APIView):
"""
POST login/
"""
permission_classes = (permissions.AllowAny,)
queryset = User.objects.all()
def post(self, request, *args, **kwargs):
username = request.data.get('username', '')
password = request.data.get('password', '')
user = auth.authenticate(request, username=username, password=password)
if user is not None:
auth.login(request, user)
serializer = LoginSerializer(self.queryset,
data={
'token': jwt_encode_handler(jwt_payload_handler(user)),
'username': username,
'password': password,
}
)
if serializer.is_valid():
return Response(serializer.data)
return Response(status=status.HTTP_401_UNAUTHORIZED)
答案 0 :(得分:1)
您只需将令牌转储到json中,甚至不使用序列化程序。您在此处提供数据和格式,因此您无需验证任何用户输入。
class UserLogin(APIView):
"""
POST login/
"""
permission_classes = (permissions.AllowAny,)
queryset = User.objects.all()
def post(self, request, *args, **kwargs):
username = request.data.get('username', '')
password = request.data.get('password', '')
user = auth.authenticate(request, username=username, password=password)
if user is not None:
auth.login(request, user)
return Response({'token': jwt_encode_handler(jwt_payload_handler(user)),
'username': user.username})
return Response(status=status.HTTP_401_UNAUTHORIZED)