Introduction to JSON Web token: 74846723
1. Installation
$ pip Install DJANGORESTFRAMEWORK-JWT
2. Add a configuration
Rest_framework = { 'default_authentication_classes': ( ' rest_framework.authentication.BasicAuthentication', ' Rest_framework.authentication.SessionAuthentication', ' Rest_framework_jwt.authentication.JSONWebTokenAuthentication', ),}
3. Add a URL
from Import Obtain_jwt_token # ... = [ ' ', # ... # JWT Authentication interface URL (r'^api-token-auth/', Obtain_jwt_token),]
Post the user name and password to the interface, which returns the token string.
4. Actual use
The actual use of login, is the post user name and password, and then the system to verify the correctness of the user name and password, the correct return token, then the above URL is based on the Django Auth to verify. Then the hints for validation may not be well controlled, so write the login verification yourself and return tokens after the validation is passed.
Validation is placed in the serializer:
#logging in to a column classclassUserserializer (serializers. Modelserializer): Username= serializers. Charfield (max_length=11) #password = Passwordfield (write_only=true) defValidate (self, attr): User= Authenticate (username=attr["username"], password=attr["Password"]) ifUser:returnattrElse: Raiseserializers. ValidationError ("User name or password error ...") classMeta:model=userprofile Fields= ('username','Password')
View:
#User Login/Personal informationclassUserviewset (mixins. Createmodelmixin, Mixins. Retrievemodelmixin, Mixins. Updatemodelmixin, Viewsets. Genericviewset): Queryset=UserProfile.objects.all ()#The dynamic Return serializer class returns Serializer_class by default and can override defGet_serializer_class (self):ifSelf.action = ="Retrieve":#action:update partial_update returnUserinfoserializerelifSelf.action = ="Create": returnUserserializerreturnUserinfoserializer#dynamic load Permission validation defget_permissions (self):ifSelf.action = ="Retrieve": return[Permissions. IsAuthenticated ()]elifSelf.action = ="Create": return [] return [] defCreate (self, request, *args, **kwargs):#User Login Return tokenSerializer = Self.get_serializer (data=request.data) serializer.is_valid (raise_exception=True)#re_dict = serializer.data Post DataPayload = Jwt_payload_handler (self.request.user)#Print (payload)Token_str =Jwt_encode_handler (payload) Headers=self.get_success_headers (serializer.data)returnResponse (Token_str, Status=status. http_201_created, Headers=headers)
Official website: http://getblimp.github.io/django-rest-framework-jwt/
Django-rest-framework's JSON Web token way to complete user authentication