json web token的介绍:https://blog.csdn.net/kevin_lcq/article/details/74846723
1. 安装
$ pip install djangorestframework-jwt
2. 添加配置
REST_FRAMEWORK = { ‘DEFAULT_AUTHENTICATION_CLASSES‘: ( ‘rest_framework.authentication.BasicAuthentication‘, ‘rest_framework.authentication.SessionAuthentication‘, ‘rest_framework_jwt.authentication.JSONWebTokenAuthentication‘, ), }
3. 添加URL
from rest_framework_jwt.views import obtain_jwt_token #... urlpatterns = [ ‘‘, # ... # jwt的认证接口 url(r‘^api-token-auth/‘, obtain_jwt_token), ]
向该接口post用户名和密码,会返回token串。
4. 实际使用
实际使用登录时,是post用户名和密码,然后系统验证用户名和密码的正确性,正确返回token,那么上面的url是根据django的auth去验证的。那么对于验证的提示可能不太好控制,所以自己写登录验证,在验证通过之后,返回token。
验证放在serializer中:
# 登录 列化类 class UserSerializer(serializers.ModelSerializer): username = serializers.CharField(max_length=11) # password = PasswordField(write_only=True) def validate(self, attr): user = authenticate(username=attr["username"], password=attr["password"]) if user: return attr else: raise serializers.ValidationError("用户名或密码错误...") class Meta: model = UserProfile fields = (‘username‘, ‘password‘)
View:
# 用户登录/个人信息 class UserViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): queryset = UserProfile.objects.all() # 动态 返回序列化器类 默认返回serializer_class,可以重写 def get_serializer_class(self): if self.action == "retrieve": # action:update partial_update return UserInfoSerializer elif self.action == "create": return UserSerializer return UserInfoSerializer # 动态加载权限验证 def get_permissions(self): if self.action == "retrieve": return [permissions.IsAuthenticated()] elif self.action == "create": return [] return [] def create(self, request, *args, **kwargs): # 用户登录返回token serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) # re_dict = serializer.data post 的数据 payload = jwt_payload_handler(self.request.user) # print(payload) token_str = jwt_encode_handler(payload) headers = self.get_success_headers(serializer.data) return Response(token_str, status=status.HTTP_201_CREATED, headers=headers)
官网:http://getblimp.github.io/django-rest-framework-jwt/
原文地址:https://www.cnblogs.com/yuqiangli0616/p/9462037.html
时间: 2024-10-15 13:35:47