本章采用的是携带jwt的方式
首先我们需要搭建好我们的目录结构,如下图所示:
utils代码:
from apps import models
def jwt_response_payload_handler(token, user=None, request=None):
"""
自定义jwt认证成功返回数据
token: jwt 字符串
user: 当前登录用户对象
request: 当前请求对象
"""
return {
'token': token,
'id': user.id,
'username': user.username
}
def get_user_obj_by_account(account):
try:
user = models.User.objects.get(username=account)
return user
except models.User.DoesNotExist:
return None
?
serializer代码:
# 登录序列化器
class CustomJSONWebTokenSerializer(Serializer):
def __init__(self, *args, **kwargs):
"""
Dynamically add the USERNAME_FIELD to self.fields.
"""
super(CustomJSONWebTokenSerializer, self).__init__(*args, **kwargs)
self.fields[self.username_field] = serializers.CharField()
self.fields['password'] = PasswordField(write_only=True)
@property
def username_field(self):
return get_username_field()
def validate(self, attrs):
# 账号密码字典
credentials = {
self.username_field: attrs.get(self.username_field), # "username": "xxx"
'password': attrs.get('password'), # "password":"123"
}
if all(credentials.values()): # self.context['request'], 当前请求对象
# 签发token,用账号密码得到user对象
user = authenticate(self.context['request'], **credentials)
if user:
if not user.is_active:
msg = _('User account is disabled.')
raise serializers.ValidationError(msg)
# 签发token,通过user得到payload,payload包含用户信息与包含时间
payload = jwt_payload_handler(user)
# 在视图类中,通过序列化对象,拿到user和token
return {
# 签发token:通过payload签发出token
'token': jwt_encode_handler(payload),
'user': user
}
else:
msg = _('Unable to log in with provided credentials.')
raise serializers.ValidationError(msg)
else:
msg = _('Must include "{username_field}" and "password".')
msg = msg.format(username_field=self.username_field)
raise serializers.ValidationError(msg)
models代码:
class User(AbstractUser):
name = models.CharField(max_length=64)
pwd = models.CharField(max_length=64)
wechat = models.CharField(max_length=32)
phone = models.CharField(max_length=16)
class Meta:
db_table = 'qq_user'
verbose_name = '用户信息'
verbose_name_plural = verbose_name
urls代码:
from django.contrib import admin
from django.urls import path
from rest_framework_jwt.views import obtain_jwt_token, verify_jwt_token
from apps import views
urlpatterns = [
path('admin/', admin.site.urls),
# path('login/', obtain_jwt_token),
path('login/', views.LoginView.as_view()),
path('verify_token/', verify_jwt_token),
path('register/', views.RegisterView.as_view()),
]
postman测试效果:
?
|