Setting up our Project
File Structure
This is the file structure after completing all the steps in this article.
Step 1: Create a virtual environment and activate it.
Step 2: Install Django and start your project.
Step 3: Create a project named TokenAuth
django-admin startproject TokenAuth
Step 4: Start an app named token_auth_app by moving to the project folder.
cd TokenAuth
python manage.py startapp token_auth_app
Step 5: Add your app to the installed apps in setting.py.
'token_auth_app.apps.TokenAuthAppConfig'
Step 6: To Set up Django channels for the backend part. Install Django-channels
python -m pip install -U channels
Step 7: Add channels to the installed apps.
INSTALLED_APPS = [
'token_auth_app.apps.TokenAuthAppConfig',
'channels'
]
Step 8: Installing the REST framework is required to create token authentication for backend applications. For token authentication, the rest framework’s auth token package, which contains a Token model, is used.
pip install django-rest-framework
Step 9: Install cors.
pip install django-cors-headers
Step 10: Add both to the INSTALLED_APPS and also token auth package.
INSTALLED_APPS = [
'token_auth_app.apps.TokenAuthAppConfig',
...
'channels',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
]
Step 11: Set ALLOWED_HOSTS to *, Also, add the cors middleware to the MIDDLEWARE list The cors setup is done so that the host allows all the origins and we can communicate with the backend application.
ALLOWED_HOSTS = ["*"]
CORS_ALLOW_ALL_ORIGINS = True
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
# -----------------------------------------
'corsheaders.middleware.CorsMiddleware',
# -----------------------------------------
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Token Authentication in Django Channels and Websockets
Prerequisites: Django, WebSockets, Django channels, Token authentication
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).