EDIT: url is culprit I think. In working login.html case I got in log:
FINE: Security checking request POST /SesamaMaven/protected/admin/j_security_check
And in AJAX-version I got:
FINE: Security checking request POST /SesamaMaven/
I configured authentication in Glassfish with JDBCRealm and it seems to be working with normal login.html like that:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Login Form</title>
</head>
<body>
<form method="post" action="j_security_check">
<p>You need to log in to access protected information.</p>
<table>
<tr>
<td>User name:</td>
<td><input type="text" name="j_username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="j_password" /></td>
</tr>
</table>
<p><input type="submit" value="Login" /></p>
</form>
</body>
</html>
My problem is that when I try to implement same with AJAX, it is not working. Is there any possibility to get that working?
HTML
<form class="navbar-form pull-right">
<input class="span2" type="text" placeholder="Email" name="j_username" id="username">
<input class="span2" type="password" placeholder="Password" name="j_password" id="password">
<button type="button" class="btn" id="btnSignIn">Sign in</button>
</form>
JS
$('#btnSignIn').click(function() {
$.ajax({
type: "POST",
contentType: "application/text",
url: "j_security_check",
// This is the type what you are waiting back from the server
dataType: "text",
async: false,
crossDomain: false,
data: {
j_username: "admin",
j_password: "paSSWORD"
},
success: function(data, textStatus, xhr) {
alert('Thanks for your signin in! ' + xhr.status);
window.location = "/SesamaMaven/protected/adminWelcome.html";
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
window.location = "/SesamaMaven/index.html";
alert(' Error in signIn-process!! ' + textStatus);
}
});
});
QUESTIONS
1) What is the correct contentType: "application/text"?
2) Is the URL tag correct one or should I use action?
3) How about parameters username and password in case like that?
Glassfish tries to authenticate but there is no user and password.
contentType: "application/text" is the culprit. I just commented that line out and everything started to work.
One problem there still is. When there is an error in authentication, it does redirect to index.html but there is no css and the address bar includes the address where it should go in succeeded case /protected/adminWelcome.html.
I add those code in login.html file.
On development process, I feel lazy to type username and password
xhttp.open("POST", "j_security_check", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("j_username=MY_USERNAME&j_password=MY_PASSWORD");
location.reload(true);
It seems that, you are try to infor user when they input wrong credential.
In my case, I have login.html and error-login.html exactly the same,
except the error-login.html has a text "You are input wrong password or username"