Django-rest-framework's JSON Web token way to complete user authentication

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.