I’m trying to create a C++ application to login in a Django server. I’ve been looking for this but I haven’t found a solution to my specific question.
I’m using one of the examples of libcurl website to do the request:
#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1/");
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
/* always cleanup */
curl_easy_cleanup(curl);
}
return 0;
}
And I’ve found an option to put user and password:
curl_easy_setopt(curl, CURLOPT_USERPWD, "luis:123456");
But the problem is that I don’t know how Django can recognise this curl option.
Other posibility would be to complete the form that Django provides to login. The form that I’m using is:
<html><body>
<form method="post" action="/login">
{% csrf_token %}
{% if form.errors %}
<p class="error">Login error</p>
{% endif %}
<table>
<tr>
<td>Username</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>Password</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="login" />
</form>
</body>
</html>
With this option, my problem is that I don’t know how get and complete the form using C++ and curl.
You would need to send a POST request with the login form data to the login URL – unless the Django web-application provides a different login mechanism which is usually not the case.
When you send the POST data and the Django login form processing did successfully authenticate the user you’ll get back a cookie that you’d to store and use in the subsequent requests.
Also note that the login form uses the
csrf_tokentags which means if you don’t send acsrftokencookie and a token with the form data with your request, Django will reject the request. I’d suggest you take a look at the HTTP request a browser does when you load and submit the login page. All modern browsers have nice debug tools to monitor the requests.Alternatively, in case you have control over the Django web-application, you can disable the CSRF token validation in the view function for the login page.