Full stack Django: QuickStart JWT Certification and React/redux (i)

Source: Internet
Author: User
Tags auth pack virtual environment





This article describes how to quickly get started with the application development of Django and React/redux SPA (Single page Web application: one Web application).

react jwt


It's hard to imagine a Django application without user authentication and authorization. So we start with a simple application that validates a user and executes an authorization request to the API.


react jwt authentication

In addition, you will learn how to use Redux-router, redux-persist local state persistence storage, react jwt localstorage and write a simple reactstrap based UI application (react implementation base based on Bootstrap 4)



In the first part of the tutorial, we will create a simple Django background application based on JWT Token authentication. The second part shows how to build the React/redux front-end application, and the third part shows how to implement JWT refresh Token workflow.



Finally, you will implement a lightweight, scalable, back-end and React/redux front-end application system based on Django. Before starting the tutorial, you must install the Python 3.6 (the Ubuntu environment ensures that the Python3.6-dev and python3.6-venv packages are installed). What is JWT



JWT is a stateless authorization method. Server-generated Token can only be kept on the client. The JWT itself can contain additional loads. It can be a user name, e-mail message, jwt and react or user right that is signed by a server-side key. This is handy when you split the Django monolith into different servers without sharing a user database, jwt react express  even when you perform authenticated backend requests in other technologies.



You can read more about JWT in a simple 5-step understanding of JWT (JSON Web tokens).



The JWT authorization endpoint can provide two Token types--a short cycle access Token and a long cycle refresh Token. You can use short period access Token to perform API calls on different services, and using a long cycle refresh Token is a good time to get a new access token when it expires.

react login jwt


Long-period refresh Token allows a user to ask the user for a username and password when they first authenticate, react jwt localstorage and the user stays for a period of time.



Continuously flushes short period access Token, react native jwt allowing synchronous Token payload (remember user name or permissions)



Another reason for the two kinds of Token is the ability to prevent users from receiving new access tokens. Server-Side

react redux node mongodb jwt authentication


Server-side projects are simple. We start by building a virtual environment and install the Django dependency pack


$ mkdir backend/&& CD backend/
$ python3.6-m venv env
$ source env/bin/activate
$ pip install coreapi Django djangorestframework \
      djangores TFRAMEWORK-SIMPLEJWT
$ pip freeze > Requirements.txt
$ django-admin startproject config.


We installed the Coreapi dependency pack to automatically generate an API pattern that describes what resources are available, what URLs are, how they are represented, and what operations they support.



And the DJANGO-REST-FRAMEWORK-SIMPLEJWT package, which implements JWT authorization and authentication through a refresh and access token.



Edit config/settings.py to enable it


Installed_apps = [
    ...
    ] Rest_framework ',
]
# Rest Framework
Rest_framework = {
    ' default_permission_classes ': (
        ' rest_framework.permissions.IsAuthenticated ',
    ),
    ' default_authentication_classes ': (
        ' rest_framework_simplejwt.authentication.JWTAuthentication ',
        ' Rest_framework.authentication.SessionAuthentication ',
    ),
}


We add rest_framework to the Installed_apps of the settings, by default using Isauthenticate to protect all API resources while starting jwtauthentication and sessionauthentic ation We will use standard Django session authentication to access the protected mode view.



Edit config/urls.py


From Django.conf.urls import URL, include from
django.views import generic from
rest_framework.schemas import Get_schema_view
from rest_framework_simplejwt.views import (
    tokenobtainpairview,
    Tokenrefreshview ,
)
Urlpatterns = [
    url (R ' ^$ ', generic. Redirectview.as_view (
         url= '/api/', Permanent=false)),
    URL (r ' ^api/$ ', Get_schema_view ()),
    URL (r ' ^api/auth/', include (
        ' Rest_framework.urls ', namespace= ' rest_ Framework "),
    url (r ' ^api/auth/token/obtain/$ ', Tokenobtainpairview.as_view ()),
    URL (r ' ^api/auth/token/ Refresh/$ ', Tokenrefreshview.as_view ()),
]


We have enabled the Schema view, the session authentication URL from Django-rest-framework, and the JWT authentication Tokenobtainpoarview and Tokenrefreshview.



In the final step, let's create a simple echo API endpoint to test the call to the front end. When we are authorized. For the demo project, we can add it directly to the config/urls.py.


From rest_framework import views, serializers, status from
rest_framework.response import response
Class Messageserializer (serializers. Serializer): Message
    = serializers. Charfield ()
Class Echoview (views. Apiview):
    def post (self, request, *args, **kwargs):
        serializer = Messageserializer (data=request.data)
        Serializer.is_valid (raise_exception=true) return
        Response (
            serializer.data, Status=status. http_201_created)
Urlpatterns = [
    ...
    ] URL (r ' ^api/echo/$ ', Echoview.as_view ())
]


Running the server


$./manage.py Migrate
$/manage.py createsuperuser
$./manage.py Runserver


Open http://127.0.0.1:8000 Login and view the automatic generation mode of our API.






Open http://127.0.0.1:8000/api/auth/token/obtain/Enter authentication and see we have new access and refresh token in response






Open Http://127.0.0.1:8000/api/echo, we can check the echo endpoint.






Next, we're ready to build the front-end application, let's go to the second part of the tutorial


Related Article

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.