DRF基于jwt实现后端登录认证
from django.contrib.auth import authenticate
from rest_framework_jwt.settings import api_settings
from rest_framework import serializers
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
class LoginSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
def validate(self, data):
user = authenticate(**data)
if user and user.is_active:
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
self.context['user'] = user
self.context['token'] = token
return data
raise serializers.ValidationError("无效的用户名或密码")
# 使用示例
# from django.contrib.auth import authenticate
# user = authenticate(username='myusername', password='mypassword')
# if user:
# payload = jwt_payload_handler(user)
# token = jwt_encode_handler(payload)
# print(token)
这段代码定义了一个序列化器,用于处理登录请求并生成JWT token。在validate
方法中,它使用Django的authenticate
方法来验证用户凭据。如果认证成功,它将生成JWT payload并编码为token,然后将用户和token存储在上下文中。如果认证失败,它将引发一个验证错误。
评论已关闭