Answer the question
In order to leave comments, you need to log in
What is the best way to authorize a REST API in a JS (client) and PHP (server) assembly?
Good day,
Actually, I found a partial answer here , but not completely.
The essence of the project is as follows:
1. JS, HTML system, a lot of pages.
2. Server handler PHP, MySQL.
the only logical way is the HTML5 LocalStorage which will contain the token and retrieve the token from the LocalStorage with each request.
Questions:
1. Is there a better way?
2, Should I abandon LocalStorage and switch to PHP variable? I don’t see much difference, only that the token is not visible on the client side.
3. Is it worth it to shaman on the server side? Sessions or Cookies? I do not see the point, but still, maybe I missed something.
4. how to secure all this?
Thanks in advance
Answer the question
In order to leave comments, you need to log in
In general, so, 2 days of shamanism and a bunch of all sorts of useless articles, I figured everything out.
The implementation is pretty simple. only instead of cURL used AJAX.
PHP script , explanation here .
I did not use the last item (Create an Authorize Controller) until I understood what it was for. If anyone can please explain.
Now JS:
1. Get the token via AJAX.
$.ajax({
url: "token.php", // Линк API обработчика.
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("testclient:testpass")); // Логин и пароль по мануалу, заменить на свои после интеграции и сделать hash или md5 для пароля.
},
type: 'POST',
dataType: 'json',
data: {grant_type:"client_credentials"},
success: function (data) {
console.log(JSON.stringify(data.access_token)); // Проверка что токен получен.
localStorage.setItem('token', data.access_token); // Помещаем в LocalStorage для последующей проверки на других страницах.
isAuth(data.access_token); // Запуск глобальной функции для проверки доступа, авторизирован или нет пользователь.
}
});
function isAuth(token){
$.ajax({
url: "resource.php",
type: "POST",
dataType: "json",
//contentType: "application/json",
data: {access_token : token},
success: function (data) {
console.log(JSON.stringify(data));
// Функция обработчик.
}
});
}
I recommend that you use the open standard OAuth . For the API, I use Bearer token-based authorization. Here is an example from Twitter. All major social networks have corresponding solutions.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question