testing_html.html file

After submitting a post request with a username and password, the file will be used to store the token that was received upon successful authentication. The TokenAuthMiddleWare in middlewares.py will assist us with this. Then, using Django channels, we will connect to a WebSocket to the backend and authenticate using the token.

HTML
<!DOCTYPE html>
<html>
    <head>
        <title>Token Auth</title>
    </head>
    <body>
        <input type ="text" name = "username" id = "form_username" /><br>
        <input type = "text" name = "password" id = "form_password" /><br> 
        <button onclick = "loginViaBackend()"> Login </button>
    
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

        <script>
            function createSocket(token) {
                ws_path = "ws://localhost:8000/?token="+token ; 
                socket = new WebSocket(ws_path) ; 

                socket.onopen = function(e) {
                    console.log("Connected") ; 
                    socket.send(
                        JSON.stringify(
                            {
                                "command" : "Say hello !" , 
                                "data_string" : "This is the data string !" , 
                            }
                        )
                    ) ;
                }
                
                socket.onclose = function(e) {
                    console.log(e) ; 
                }
                
                socket.onmessage = function(data) {
                    data = JSON.parse(data.data) ; 
                    console.log(data) ; 
                    console.log(data["command_response"])
                }
            }

            function loginViaBackend() {
                console.log("The function was run !") ; 
                var username = document.getElementById("form_username").value ; 
                var password = document.getElementById("form_password").value ; 
                
                console.log(username) ; 
                console.log(password) ; 

                payload = {
                    "username" : username ,
                    "password" : password , 
                }
                
                $.ajax(
                    {
                        "type": "POST" , 
                        "dataType" : "json" ,
                        "url" : "http://localhost:8000/api/login/" ,
                        "timeout" : 5000 , 
                        "data" : payload , 
                        "success" : function(data) {
                            console.log(data) ; 
                            token = data["token"] ; 
                            createSocket(token) ; 
                        },
                        "error" : function(data) {
                            console.log(data) ; 
                        }
                    }
                ) ;
            }
        </script>
    </body>
</html>

Code explanation: 

Once you click the login button the function loginViaBackend function is run and it makes a post request to the api/login URL which we have just created in the backend. (we are using ajax for making the post request), In the loginViaBackend function, we access the values of the username and the password and then send it via the post request. After the successful request we get the token from the backend as the successful request of a username and the password returns the token. 

Create a superuser 

python manage.py createsuperuser

I have created a superuser named, testuserone with password testing123, and suraj with password 123.

 

Migrate database

With the token, we run the function name createSocket(token), this takes and creates a WebSocket request to the backend server. Before running this part make sure to makemigrations and migrate the database. 

python manage.py makemigrations
python manage.py migrate

Run the server in the localhost with port 8000 and create a socket connection with a token parameter in the query params of the request. 

python manage.py runserver

path for WS connection, 

ws_path = "ws://localhost:8000/?token="+token ; 

The token is passed from the success parameter of the ajax post request. Then we create WS connection, once you get connected you will receive the data which was sent by the consumer. 

Output: 

First, we entered the correct login and password, which caused the token id to appear; second, we entered the incorrect password, which prevented the token from appearing.

To open the HTML file just copy the path of the file and paste it into your browser, or go to the folder and double-click on the file to launch the HTML file.



Token Authentication in Django Channels and Websockets

The most popular Django topics right now are WebSockets and Django channels because they make it possible to communicate quickly and easily while working in real-time without constantly refreshing the page. When working with the Django templating engine alone and not the REST framework, the authentication method that Django channels employ is session authentication. The user who is currently logged in is also reflected in the Django channels auth system.

// This is not possible in websockets .

var socket = new WebSocket(“path_of_the_socket” , headers = { “Authorization’: “token token_string” })

Well, using web-based authentication is one way you could reach your goal. Returning a cookie to the website allows you to connect to the WebSocket server once more with the cookie in hand, authenticate, and then continue. However, cookie-based authentication can be extremely unreliable and have various problems. Therefore, to address this issue, we can convey the authentication token from the socket’s query parameters and then build a new authentication stack that will sit on top of the existing ones when routing WebSocket connections.

However, working with the rest framework with token authentication or JWT authentication is not simple for WebSockets and channels; as a result, it can be challenging to log in to the user via channels and sockets when using token authentication or the rest framework. There is no way you can send auth/JWT tokens to the headers of a WebSocket like that of a simple post or get a request in the Authorization header.

Note: This process is totally asynchronous because WebSockets and channels work with ASGI (Asynchronous server gateway interface). 

Similar Reads

Setting up our Project

File Structure...

Code Implementation

Setting up files one by one:...

testing_html.html file

After submitting a post request with a username and password, the file will be used to store the token that was received upon successful authentication. The TokenAuthMiddleWare in middlewares.py will assist us with this. Then, using Django channels, we will connect to a WebSocket to the backend and authenticate using the token....