I have been learning the django rest framework and i have created a few api calls. I have also used the django rest framework TokenAuthentication to give each user in my database a token to authorise the call. I was just wondering what is the best way to pass the token into javascript? Do i have to pass the token to a django view? Or is there a way to pass the token into javascript directly?
As i am new to this I want to be learning the best practices, so any help will be appreciated.
You can pass the authentication token using ajax inside the headers.
$.ajax({ url: '/api/v1/get-users',
type: 'get',
headers: {'Authorization': 'Token <your token>'},
success: (e) => {
console.log(e)
},
error: (e)=>{
console.log(e)
}
})
Related
I am building my first Laravel application and have a problem with the ajax request and specifically the CSRF verification.
I have followed all the steps in the documentation but it is not exactly doing what is said in there.
The App\Http\Middleware\VerifyCsrfToken middleware, which is included in the web middleware group by default, will automatically verify that the token in the request input matches the token stored in the session.
I have been manually concatenating 'test' to all CSRF tokens from the meta tag and the responses is still going through which it shouldn't of course.
Do I now have to manually Verify the CSRF token? If not what's the best practice to verify a token send in the headers of a jquery ajax post request through the controller?
I don't really understand what error that you encountered, but here's some Ajax setup and callin that i usually do.
//Setup header before callin ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//Ajax call update
$.ajax({
url: '/posts/1/update',
type: 'POST',
data: {
id: 123,
content: 'Abc123',
},
complete: function (response, xhr, settings) {
//Do something
}
});
You don't need to edit your VerifyCsrfToken middleware to make this work.
I have laravel 5.4 running with passport. Which is realy nice.
My question is now how can I get the acces token for my ajax calls?
What works is this
<script>
function getData() {
$.ajax({
headers: {
Authorization: "Bearer " + "eyJ0eXAiOiJK..."
},
url: '/api/records/',
type: 'GET',
success: function (result) {
console.log("yay");
}
});
}
</script>
What have I to do to NOT hardcode the bearer token?
Or what to do better? Is this the right approach?
Is there a magic method where I can get the session and use the session to auth a user? Thanks for your help!
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.
I'm using web api without deep understanding what it is, just knowing that each editable entity become a resource, that means has the uri, when web api provides the interpretation of PUT, POST, GET, DELETE HTTP commands to support CRUD operations. But what if for tracing/logging purpose I need to send correlation token together with e.g. GET request? Are there any recommendations and techniques to add to the HTTP request/routing "technical parameters"?
I have found something that need to be tested https://webapicorrelator.codeplex.com/ But actually I would prefer just to understand how it could work...
Or just add it to the heder using jquery ajax headers:
return $.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
url: url,
data: { ElectrodeId: electrodeId },
headers: { "X-CorrelationToken": correlationToken },
method: "POST",
dataType: "json",
success: function (data) {
}
I am sending a POST AJAX request using Angularjs and its $http module to Django server. Here is an example:
$http({
method: 'POST',
url: '/url/',
data: 'test data'
}).
success(function(data, status, headers, config) {
doSomeStuffWhenSuccess();
});
The problem is what I get in Django. No matter what I send the data is always the key of QueryDict object and value of that is always an empty list.
<QueryDict: {u'test data': [u'']}>
I don't have a clue why. What am I missing?
I use almost default created Django application with default middlewares only. I created only a view and set an url in url config. Version of Django is 1.3. And I configured angular's $http module to always send a header containg csrf token to satisfy Django.
I resolved this with jQuery param function. I think it's more elegant solution.
$http({
method: 'POST',
url: '/url/',
data: $.param({test: data})
})
Now it works like I wanted.
I believe django thinks you are sending a urlencoded form, ex. key=value&key2=value2...
if you'd try:
$http({
method: 'POST',
url: '/url/',
data: 'test=data'
})
You should get
<QueryDict: {u'test': [u'data']}>
You can always obtain the data (raw body content) as follows:
request.body
Hope this is what you are looking for.