(I am not talking about authenticating calls to RESTful API. I am talking about creating login logic for user via RESTful API.)
When user access any page of my site, a servlet filter
will intercept the request and check if necessary authentication info
exists in session
. If not exists, user will be directed to login page.
On the login page, an ajax call is made to a RESTful API on server with username and password. Depending on the return status of that RESTful API, the JavaScript on the page will decide whether let user into the site. Note that the actual authentication logic is still carried out on server side. Client JS only acts based on the result from server.
On the server, the RESTful login API will check the submitted username/password and see if it is contained in DB. If exists, it will store necessary authentication info
into the session
so future requests from the same client will not be blocked.
My questions are:
Is this login logic sound?
Because
session
is involved, the RESTful login API is kind ofnot stateless
. So is it still RESTful?
Here's my code:
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');
}
}
login.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>