如何使用JavaScript创建登录身份验证客户端?

时间:2020-06-07 13:35:13

标签: javascript api rest authentication client

我想获取或获取用户凭据(例如用户名和密码)以使用服务器端的api网址登录我们的网站。我在客户端上工作。我一直在寻找互联网上的教程,但找不到。任何人都可以给我这样的开端或领导。

2 个答案:

答案 0 :(得分:1)

对于身份验证,您将需要一个后端。 鉴于您在询问有关JS的信息,所以我假设您使用的是node + express.js后端。

您需要做的第一件事,是从客户端获取用户名/电子邮件和密码,然后通过请求将其发送到express.js服务器。

在服务器中,存储用户名和密码(如果可能,请在存储之前进行加密)。 之后,使用jwt也称为JSON网络令牌。该库可用于所有流行语言,您可以从this link中找到它。 之后,使用此库将凭证(以json格式)转换为jwt令牌。

此令牌是一个较长的加密字符串。返回此字符串作为响应。

现在回到客户端,使用localStorage.setItem('token', token);将此令牌存储在本地存储中 将令牌保存在本地存储中。

对于每个后续请求,请将此令牌传递到标头中。

您可以对登录执行相同的操作。因此,代替存储到数据库,而是匹配凭据。

答案 1 :(得分:0)

不应在客户端进行身份验证。

说明:

想象一下,您是一家只允许其员工进入的大公司的保安。
每位员工随身携带一张带有唯一ID和密码的卡。
有人出现在门口,问你让他们进去。
您要求该人为其卡提供ID和密码。当他给一张带有其凭据的卡时,您不要让他进入,因为您知道他可能在撒谎,甚至认为他给您的卡上都印有公司的徽标,您知道此卡可以假的。
您唯一需要依靠的是此卡上的ID和密码。
现在,您必须转到公司的数据库,并检查ID和密码的组合是否与他给您的卡上的ID和密码相匹配。

现在,尝试输入的人员代表用户,您代表网站的身份验证系统,而公司代表您的网站。

您无法验证用户客户端。完成的方式是:用户发送其凭据,现在在服务器上对照数据库检查这些凭据以查看是否存在匹配项。如果是,则服务器允许该用户进入网站(换句话说,服务器发送响应)

现实生活中的示例: [编辑]

这是一个发送到客户端的名为Home_login.html的页面,其中包含以下代码:

/*
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=somename@hotmail.com&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=somename@hotmail.com&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":"someemail@hotmail.com",
  "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>

现在,您已将正确格式(JSON)的数据发送到服务器,客户端可以做的就是等待响应。

发生认证的位置

客户只是在等待服务器上的某些答复,客户无法执行任何操作。

服务器具有凭据,检查其是否与数据库中的任何记录匹配,并取决于服务器决定如何响应客户端。

(请记住,客户端正在等待响应并会检查响应代码。这是上面Java脚本中的功能:

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 {

                    }
                }
            }



如果存在匹配项,则说明用户已通过身份验证,因此会发生以下情况: 1-服务器将响应发送回等待的客户端。该响应的响应代码= 200。 2-同样,在该响应中,服务器告诉客户端(客户端在其上工作的浏览器)创建一个cookie,该cookie的值= randomString 记住以后的Cookie重要

如果没有匹配项: 1-服务器还将响应发送回等待的客户端。但是这次响应代码不是200(404)。在该响应中,他可以发送如下所示的JSON对象:

{
  "message":"Wrong credentials-no user found"
}

现在,这是服务器告诉客户端是否已使用响应代码进行身份验证的方式。 现在,在客户端运行的代码(javascript aboce中的函数)可以根据响应代码来决定要做什么。如果它是200(已验证),则可以将用户重定向到仪表板页面。如果不是200,则可以显示从服务器收到的消息(在这种情况下为“错误的凭据-未找到用户”)

现在有最后一件事

记住上面随服务器响应发送的cookie。 该cookie将保留在客户端计算机上,直到他关闭浏览器。 并将其与对服务器的每个新请求一起发送,从而使服务器知道该用户已经通过身份验证,因此它可以为他提供正确的内容。

查看此视频https://www.youtube.com/watch?v=j8Yxff6L_po