I wanted to write auth backend for both mobile and webapp, so I decided to go with the DRF (Django Rest Framework) token authentication.
I pretty much figured out backend via DRF documentation but regarding frontend implementation it just says "include token in the header of every http request to the API."
So my question is
With the help of Stackoverflow I figured out how to insert auth token in a single http header.
$.ajax({
url: "https://www.something.com/random",
type: 'get',
headers: {
token: "t&jdd9HJKHdss7hkjjkhdshgs",
}
});
I was wondering If I have to write this piece of code for every endpoints or is there a way cover all the endpoints without being redundant?
There are three ways how to store a token in a browser:
More here: https://scotch.io/@PratyushB/local-storage-vs-session-storage-vs-cookie
So, the only Cookie would do it automatically for you, all the rest - you would need to provide manually.
You can choose from both LocalStorage and SessionStorage, but if you want your users to be logged in next time they open a page - I would choose a LocalStorage.
Then it needs to be added manually to every API request, but you can create a helper function to make it easier:
function apiRequest(type, url) {
return $.ajax({
url: url,
type: type,
headers: {
token: localStorage.getItem("token"),
}
});
}
apiRequest("get","https://www.something.com/random").done(function(data) {
console.log(data)
})
More about localStorage here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With