django md5 auth ajax - django-authentication

I want to send javascript encrypted password to server URL (/account/login) and get an auth status that way:
var headers = {"X-CSRFToken": geo.helpers.readCookie('csrftoken')};
yajax.send({
"method": "POST",
"url": "/account/login/",
"data": {"login": "foo", "password": md5('533')},
"header": headers,
"success": function(response) { alert(response) }
})
Is there a way to authenticate not a plain password using standard mechanisms ?

Rather not. You propably have to implement your own login method based on django User model.

Related

How to send form-data with RestClient, if data received from a hash?

I have an API endpoint that requires data to be sent to it as form-data. I am using RestClient for sending the data. The problem is that I do not manage to give the data for the request in a way, that the endpoint would be able to read it. This is what I have tried:
RestClient::Request.execute(
method: :post,
url: url,
payload: {
multipart: true,
data: {
"user": "test",
"phase": "test",
"job_id": "test"
}
},
headers: { Authorization: 'Basic ' + Base64.encode64(auth_details), content_type: "multipart/form-data"}
)
Any advices how I could add the hash-data for the request in a way that the endpoint could read it as a form?
EDIT1:
The endpoint does receive the request. The endpoint is written with Flask and it tries to read the form parameters using flask.request in the following way:
request.form.get("user")
I managed to get the request working by changing the reuquest to be the following:
RestClient::Request.execute(
method: :post,
url: url,
payload: {
"user": "test",
"phase": "test",
"job_id": "test"
},
headers: { Authorization: 'Basic ' + Base64.encode64(auth_details),
content_type: "multipart/form-data"}
)

Cross Origin error on ajax OAuth authentication

I'm working on a web project using microservices. When I try to access the OAuth access token from the Authentication server through an ajax call, I get an error in the browser console like this:
Access to XMLHttpRequest at 'localhost:8080/oauth/token' from origin 'http://localhost:8090' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
My Ajax
$.ajax({
url: 'localhost:8080/oauth/token',
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic " + auth_token
},
data: {
"username": "user",
"password": "123",
"grant_type": "password"
},
success: function(data) {
console.log(data)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I tried looking up in previous stackoverflow questions and found this similar question. But the answer doesn't work for me as I'm not loading a local file. I'm loading the model from Tomcat.
I'm just a beginner in microservices and rest api in general. Any help is appreciated.

Symfony 3, "ajax request" with fetch API, and CSRF

In twig i generate a csrf token ({{ csrf_token('my_intention') }}).
In Javascript i call a controller with ajax, in fact with the Fetch API (Ajax xmlHttpRequest tried too), POST request. Argument name containing the token passed in the request is 'token=abcdef...'.
AJAX:
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function (data) {
console.log(data);
};
httpRequest.open('POST', el.getAttribute("data-url"));
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send(.......);
Fetch API:
fetch(el.getAttribute('data-url'), {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'token=' + encodeURIComponent(el.getAttribute('data-token'))
}).then(data => data.text()).then(data => {...}
In the controller action called i get the token sent as data from the POST request. I check the token like this in the controller:
$token = $request->request->get('token');
if (!$this->isCsrfTokenValid('my_intention', $token)) {
throw new InvalidCsrfTokenException("error csrf 2");
}
But Symfony say the token is not valid.
I'm not sure but i think token is not found in session variable. In isTokenValid() $this->storage->hasToken($token->getId()) return false.
In the browser, if i call the url directly, it's ok.
In twig i set the url to call in a data attribute like this data-url="{{ path('_check', {'id': transaction.id}) }}", then i read this data attribute from javascript and pass it to ajax/fetch function.
I tried ajax with jQuery $.post(... and it works. The only difference is Cookie:PHPSESSID... in the request header with jQuery not on my original code.
I don't understand, what is wrong with my code ?
Symfony 3.1.3
EDIT: resolved: i didn't pass credentials in headers request, so, no way for Symfony to find session and check token:
fetch(el.getAttribute('data-url'), {
method: 'post',
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"X-Requested-With": "XMLHttpRequest"
},
body: 'token=' + el.getAttribute('data-token'),
credentials: 'include'
}).then(data => data.text()).then(data => {
Even if you found an answer to your issue, I recommend you to take a look at this bundle which handles the token verification based on a Cookie which is defined server-side and that you should pass in each asynchronous request.
https://github.com/dunglas/DunglasAngularCsrfBundle

AJAX POST Request Hide Basic Auth Credentials

I've been researching ways to send AJAX POST requests to my API and I'm trying to understand how to pass basic auth credentials correctly.
Interface API
https://www.example.com/app/ -------> https://api.example.com/
Using this example I found on StackOverflow--couldn't anyone view the source of the JS, see my username and password in cleartext, and have access to all my API functions?
If so, how do I pass my username and password without showing it to the world?
$.ajax({
url: 'yoururl',
username : username,
password :password,
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
dataType: "text",
xhrFields:
{
withCredentials: true
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));
}
});
Yes, if you hardcode your username and password in your JavaScript, the whole world will be able to see them and use them.
You should not use basic authentication to protect web APIs. There are several alternatives as I describe in this answer. My preference is with OAuth2. Using it from a JavaScript client, you want to look at the implicit flow, which is specifically for untrusted clients.

Trigger.io Ajax Requests - with Parse Facebook User authentication

I'm trying to authenticate users from Trigger.io, ideally via Facebook.
I authenticate the user via Facebook (using the Parse Facebook module), and pass their access token, acess expiry date, and facebook Id to my call to Parse.
It is here things go wrong. Whenever I try and post this data via Ajax to the Parse REST API, I get an error in my forge/Trigger console reading:
{ type: 'EXPECTED_FAILURE', content: '{"code":107,"error":"This
endpoint only supports Content-Type: application/json requests, not
application/x-www-form-urlencoded."}', statusCode: '400', message:
'HTTP error code received from server: 400' }
The code I used to try and post this data is...
function auth(facebookId,accessToken,expirationDate) {
forge.logging.log('auth started');
forge.request.ajax({
url: 'https://api.parse.com/1/users',
headers: {
'X-Parse-Application-Id': config.parseAppId,
'X-Parse-REST-API-Key': config.parseRestKey,
'Content-Type': 'application/json'
},
type: 'POST',
dataType: 'json',
data: {
"authData": {
"facebook": {
"id" : facebookId,
"access_token": accessToken,
"expiration_date": expirationDate
}
}
},
success: function (data) {
forge.logging.log('auth finished 1');
forge.logging.log(data);
},
error: function(error){
forge.logging.log('auth finished 2');
forge.logging.log(error);
}
})//success
} //auth
I can't figure out how to send this as a JSON object/ in the correct format. If anyone has any ideas they'd be much appreciated. Thanks. Josh.
Whenever the data option passed to forge.requests.ajax is an object like in your example, what actually gets posted is a query string that represents the object. The contentType option merely allows you to set the Content-Type header, it does not effect how objects are encoded for the request.
However if the data option is just a string, then this string is used as the body of the request. You can generate a JSON string to use as the body using JSON.parse like so:
forge.request.ajax({
...
contentType: 'application/json',
data: JSON.stringify({
"authData": {
"facebook": {
"id" : facebookId,
"access_token": accessToken,
"expiration_date": expirationDate
}
}
})
});

Resources