Moving the login page to a different server in Django without the CSRF token

I have a login page that utilizes the django authentication system.

Now, I am looking to transfer just the login page to a separate server (an external login page).

My goal is to have the username and password fields on the external login page, and then log in to the django system.

I have created the HTML on the external server.

<form method="POST" action="http://djangoserver.com/">
   <input type="text" name="username">
   <input type="password" name="password">
  <input type="submit">
</form>

However, I encountered an error.

Reason given for failure:
    CSRF token missing

Upon inspecting the source code of the login page, I noticed that django automatically generates a csrf token using middleware.

    <form method="POST">
        <input type="hidden" name="csrfmiddlewaretoken" value="VEkMTu0EpmLbMVLRh4h9MOcuvcryIlA0M1USByG7R5PXkgYvMyzAhdKyq7gohpko">
            Username
            <input type="text" name="username" autofocus autocapitalize="none" autocomplete="username" maxlength="150" class="form-control" placeholder="Username" required id="id_username">
            
            Password
            <input type="password" name="password" autocomplete="current-password" class="form-control" placeholder="Password" required id="id_password">
            
        <button type="submit">login</button>
    </form>

Therefore, I believe I need to replicate the csrf token setup on the external login page.

Does anyone have any suggestions on how to achieve this?

Answer №1

Adding a csrfmiddlewaretoken field to your form is crucial for security reasons. Since the login page exists outside of the main server, you must create an endpoint within your project to generate a CSRF token, which can then be retrieved and inserted into the form using JavaScript. Here is an example of how to do this:

<form method="POST" action="http://YOUR-SITE.COM/">
   <input type="hidden" name="csrfmiddlewaretoken" id="csrf_token">
   <input type="text" name="username">
   <input type="password" name="password">
   <input type="submit">
</form>

<script>
   // Retrieve the CSRF token from the server
   fetch('http://YOUR-SITE.COM/csrf_token/')
      .then(response => response.json())
      .then(data => {
         // Assign the CSRF token to the form field
         document.getElementById('csrf_token').value = data.csrf_token;
      });
</script>

Ensure that your application's view includes the following code:

from django.http import JsonResponse
from django.middleware.csrf import get_token

def get_csrf_token(request):
    csrf_token = get_token(request)
    return JsonResponse({'csrf_token': csrf_token})

Remember to add the URL for this view to your Django server's URL configuration.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is a streamlined jQuery version of the Slider control designed specifically for mobile devices on the horizon?

Currently, I am developing a mobile web app and would like to incorporate the JQuery Slider control. http://docs.jquery.com/UI/Slider However, in order to do so, it seems that the entire JQuery core (29kb compressed & gzipped) is needed. My question ...

Using Jquery to toggle the visibility of divs based on radio button selections

I am struggling to hide the divs with the radio buttons until their title is clicked on. However, I am facing issues as they are not showing up when their title is clicked on. Any assistance would be greatly appreciated. SPIKE <!DOCTYPE html> &l ...

Jquery failing to append existing values into the DOM

I'm currently attempting to enhance an existing jQuery table structure with the following code snippet: function GetViewData(data) { $.ajax({ type: "GET", url: "/Services/Configuration/ViewServices. ...

Troubleshooting: Vue.js Component template not displaying items with v-for loop

I recently implemented a method that calls an AJAX request to my API and the response that it returns is being assigned to an array. In the template section, I am using the v-for directive to display the data. Surprisingly, it only renders once after I mak ...

Oops! The Vue star rating encountered an error because it couldn't read the length property of an undefined value at line 26 of listToStyles.js

Encountering an issue with the getRating function in Vue while using the Vue-star-rating package in Laravel. Unsure of what the problem may be. getRating(){ var pathArray = location.pathname.split('/'); v ...

Switching on the click functionality

I was able to successfully toggle a boolean variable along with some other options. However, I encountered an issue when trying to create another click function for a different button to set the boolean variable to false. Here is my code: let manageme ...

associating functions with various events that require arguments

I am working with two event listeners that trigger separate functions, but I believe it might be more efficient to have them trigger the same function instead. These event listeners are monitoring keystrokes and the mouse wheel. $(document).mousewheel(on ...

Tips for preventing multiple counter buttons from conflicting with one another

Currently, I am in the process of creating an online restaurant platform that allows customers to place food orders. To streamline this process, I am developing individual cards for each food item available on the menu. In addition, I am implementing butto ...

Is there a way to eliminate spaces from a string using react-native?

As a user of react-native, I've encountered an issue with inconsistent line breaks when inputting long strings on the screen. For example: https://i.sstatic.net/32RwW.jpg I aim to achieve consistent string wrapping as shown in the image below: htt ...

What is the best way to attach 'this' to an object using an arrow function?

Consider having an object named profile which consists of properties name and a method called getName (implemented as an arrow function). profile = { name: 'abcd', getName: () => { console.log(this.name); } } I am interes ...

Is it possible to use Node.js child processes without carriage returns?

My Node.js script is set up to handle some database operations by creating child processes using the spawn functionality. However, I encountered a strange issue where the output stopped displaying carriage returns. Here's an example of what was happen ...

Tips for resolving the Range issue with jQuery-UI slider and activating a function when changes are made

I created a simple form that calculates an estimated price based on quantity and one of three options. Then, I attempted to integrate a jQuery-UI slider into the form. However, I encountered an issue where the slider was displaying values outside of the sp ...

What is the correct way to define models and serializers in Django REST Framework?

We have embarked on the development of a mobile web application utilizing the following technology stack: - Python - Django with SQLite DB - Django REST - Ionic Cordova - Angular JS This application is a quiz platform where users answer questions ...

How can I customize the <span> element created by material-ui?

Is there a way I can customize the appearance of the <span> tag that is produced when using the Checkbox component from the material-ui library? Essentially, I am seeking a method to alter: <span class="MuiButtonBase-root-29 MuiIconButton-root-2 ...

An unforeseen repetition of jQuery Ajax calls

I'm currently working on an application that utilizes ajax calls to load content. However, I've encountered a situation where an ajax call goes into a loop but seems to end randomly. Below is the code sequence starting from a double click event l ...

Converting JSON information into a JavaScript array

var test=[]; $(document).ready(function(){ $.getJSON("data.json",function(data){ $.each(data,function(key,value){ test.push(value.topic); }); }); }); I have written some j ...

Unable to click on link with JavaScript using Selenium webdriver

<a id="compareCompanies" b:onclick="needsController.showQuotes = true;" href="#">Compare companies</a> Below is the Selenium Webdriver JavaScript code using Mocha: driver.wait(function () { driver.findElement(webdriver.By.id("compareCompa ...

How can you animate a MUI v4 Grid element using CSS transitions?

I was exploring the potential of using breakpoints in the MUI v4 component to control the visibility of items in my Grid System. How can I create a smooth CSS transition for b, transitioning from 0px to a defined breakpoint size of 3 for xl? Using % works ...

I'm having trouble with my "alert()" function in Vue.js

I am new to using Vue and I am attempting to trigger an alert function when a button is clicked. However, I keep encountering the error message Uncaught ReferenceError: addTask is not defined. Below are the codes I have written: <template> ...

Angular is patiently waiting for the Ajax service function to finish executing

Seeking help on retrieving the result of an $http request from my controller. Below is my service code : .service('postService', function($http, apiUrl) { return { post: function(uri, params) { $http.post(apiUrl + uri, ...