I want to fetch or get the user credentials such as username and password to login in our website with the api url from the server side. I am working on the client side. I have been looking for a tutorial on the internet but I cannot find any. Can anyone give me a headstart or lead about this.
2 Answers
For authentication you would need a backend. Given that you are asking about JS, so I assume you are using node+express.js backend.
First thing you need to do, get username/email and password from client side and send it via request to express.js server.
In server, store username and password(encrypt before storing if possible).
After this use jwt also known as JSON web token. This library is available for all popular languages and you will find it from this link.
After this use this library to convert the credentials (in json format) to jwt token.
This token is a long encrypted string. Return this string as response.
Now back in client side, store this token in local storage with localStorage.setItem('token', token);
to save the token in local storage.
For for every subsequent request, pass this token in header.
You can do the same with login. So in place of storing to database, match the credentials instead.
2 Comments
Authentication shouldn't be done on the client side.
Explanation:
Imagine you are a security guard for a big company that only allow its employees to enter.
Each employee carry a card holding a unique ID and a password for each one.
Someone just show up at the door an ask you to let them in.
You ask that person for his card an ID and a password. When he gives a card with his credentials on it, you don't let him in, because you know that he may be lying, and even thought the card he gave you has the companie's logo on It, you know that this card can be faked.
The only thing you rely on is the ID and password on this card.
Now you have to go to the database of the company and check if there is a combination of an ID and password that matches the ID and password on the card he gave you.
Now this person trying to enter represent a user, you represent the authentication system of your website, and the company represents your website.
You can't authenticate a user client side. The way It is done is: a user sends his credentials, now on the server these credentials are checked against the database to see if there is a match. If yes, the server let that user in the website (in other words the server sends a response)
Real life example: [edited]
This is a page called Home_login.html sent to the client that contains the following coode:
/*
1-
When the user click on the Login button, this page will make a POST request to the page specified by "action" which is "API/Login.php".
But because this is a POST request, the POST data sent with that request (the POST data sent are the inputs in the form: email and password), are encoded in the body and the content-type header of that request is set to "application/x-www-form-urlencoded"
So this is what inside the request sent to "API/Login.php" when the user clicks on the Login button:
POST /Login HTTP/1.1
Host: foo.example
Content-Type: application/x-www-form-urlencoded
Content-Length: 27
[email protected]&password=somepassword
2-
Now when this request reaches "API/Login.php", this page "API/Login.php" contains a code that first check the content-type of the request which is: application/x-www-form-urlencoded, which tells it that the data sent with that request are in the form of: key1=value1&key2=valu2&... (in this case it is: [email protected]&password=somepassword)
But because this is an API, the person who coded that page most probably only accept or take input data in JSON format which is different from the format: key1=value1&key2=valu2&...
JSON format :
{
"email":"[email protected]",
"password":"somepassword"
}
3-
So we are sending the data to "API/Login.php" in a format which It don't like. We need to send that data in JSON format.
To do that we write the javascript below.
NOW KEEP IN MIND THAT THIS IS ALL ON CLIENT SIDE. BUT THIS IS NOT AUTHENTICATION. THIS IS JUST SIMPLY SENDING JSON DATA TO THE SERVER ("API/Login.php"), AND NOT LETTING THE PAGE SEND IT IN THE DEFAULT FORMAT (key1=value1&key2=value2...)*/
/*When the form is submitted the function below will run, and it will:
1- Stop the default behaviour sending the data in the POOST format (key1=value&key2=value2...)
2- get the values the user typed in the input filed
3- create a JSON object containing these values
4- sending a request to "API/Login.php" with the data being the JSON object.*/
const form = document.querySelector ("form") // This selects the <form> element in the document
form.addEventListener ("submit", function (e){
e.preventDefault (); // prevent the default form's behaviour (sending POSt data)
var xhttp = new XMLHttpRequest ();
var data = new FormData (loginform); // get the data of form
var email = data.get("email"); // get the value of the <input name="email">
var password = data.get("password"); // get the value of the <input name="password">
var user = { // create the JSON object which will sent as the data in the body
email,
password
}
xhttp.onreadystatechange = function () { // this funtion will run when the server ("API/Login/.php") respond back
if (xhttp.readyState == 4 ){
var res = JSON.parse(xhttp.responseText);
if (xhttp.status != 200){ // If the response from the server has a response code of:200
}else {
}
}
}
xhttp.open ("POST", "API/Login.php"); // Create a POST request to send for the server
xhttp.setRequestHeader("content-type", "application/json"); // set the content type to json (like the server wants)
xhttp.send(JSON.stringify(user), false); // put the JSON object in the body of that request and send that request
});
<!DOCTYPE HTML>
<html>
<body>
<form method="POST" action = "API/Login.php" >
Email: <input type="text" name="email"> <br><br>
Password <input type="text" name="password"> <br><br>
<button type="submit">Login</button>
</form>
</body>
</html>
Now you sent the data in the right format (JSON) to the server and all the client can do is wait for the response.
HERE WHERE THE AUTHENTICATION HAPPENS
THE CLIENT CANNOT DO ANYTHING HE IS JUST WAITING FOR SOME REPLY FROM THE SERVER.
The server have the credentials, checks to see if they match any record in the database, and depending on that the server decides how to respond to the client.
(REMEMBER THAT THE CLIENT IS WAITING FOR THAT RESPONSE AND WILL CHECK THE RESPONSE CODE. THIS IS THE FUNCTION IN THE JAVASCRIPT ABOVE:
xhttp.onreadystatechange = function () { // this funtion will run when the server ("API/Login/.php") respond back
if (xhttp.readyState == 4 ){
var res = JSON.parse(xhttp.responseText);
if (xhttp.status != 200){ // If the response from the server has a response code of:200
}else {
}
}
}
)
If there is a match, the user is authenticated, so this is what happens: 1- The server sends a response back to the waiting client. That response has a response code = 200. 2- Also in that response the server tells the client (the browser where the client is working) to create a cookie that has a value = a randomString REMEMBER THAT COOKIE FOR LATER IT IS IMPORTANT
If there is no match: 1-The server also sends a response back to the waiting client. But this time the response code is not 200 (404). In that response he can send a JSON object which looks like this:
{
"message":"Wrong credentials-no user found"
}
Now this is how the server tells the client if he is authenticated using the response code. And now code running on the client side (the function in the javascript aboce) can decide what to do based on that response code. If it is 200 (authenticated) maybe it can redirect the user to a dashboard page. If it's not 200 it can display the message received from the server ("Wrong credentials-no user found" in this case)
Now one final thing
Remember the cookie from above sent with the server's response. This cookie will remain on the client's computer until he closes the browser. And it is sent with every new requests made to the server, allowing the server to know that this user is already authenticated, so It can server him the right content.
Check this video https://www.youtube.com/watch?v=j8Yxff6L_po