(我不是在谈论对 RESTful API 的调用进行身份验证。我是在谈论通过 RESTful API 为用户创建登录逻辑。)
当用户访问我网站的任何页面时,servlet filter
将拦截请求并检查是否有必要authentication info
存在于session
。如果不存在,用户将被引导至登录页面。
在登录页面上,使用用户名和密码对服务器上的 RESTful API 进行 ajax 调用。根据该 RESTful API 的返回状态,页面上的 JavaScript 将决定是否允许用户进入该站点。请注意,实际的身份验证逻辑仍然在服务器端执行。客户端JS仅根据服务器的结果进行操作。
在服务器上,RESTful登录API将检查提交的用户名/密码并查看它是否包含在DB中。如果存在则存储必要的authentication info
进入session
因此来自同一客户端的未来请求将不会被阻止。
我的问题是:
这是我的代码:
login.js
// login.js
$(function () {
$('#submitDiv').click(doLogin);
});
function doLogin() {
$('#resultDiv').text("start!");
user = new Object();
user.username = $('#txtUsername').val();
user.pwd = $('#txtPassword').val();
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
'type': 'POST',
'url': 'doLogin.sm',
'data': JSON.stringify(user),
'dataType': 'text',
'success': loginSuccessful,
'complete': function (jqXHR, textStatus) {
$('#resultDiv').text("complete with:" + textStatus);
}
});
}
function loginSuccessful() {
//if referrer is null, jump to dashboard, else jump to referrer.
var referer = getUrlVars()['referer'];
if (referer) {
window.location.replace(referer);
}
else {
window.location.replace('dashboard.html');
}
}
登录.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>My Cloud - Login page</title>
<link rel="stylesheet" type="text/css"
href="resources2/css/bootstrap.css">
<meta charset="utf-8">
<!--force to use the latest IE engine-->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="resources2/js/jquery-1.11.3.js"></script>
<script src="resources2/js/bootstrap.js"></script>
<script src="resources2/js/pagejs/common.js"></script>
<script src="resources2/js/pagejs/login.js"></script>
</head>
<body>
<h1>My Login Page</h1>
<div id="loginDiv">
<input id="txtUsername" type="text" value="test">
<input id="txtPassword" type="password" value="test">
<div id="submitDiv" class="btn btn-default">
Login
</div>
<div id="resultDiv"></div>
</div>
</body>
</html>