I want to secure web api for that i am using nugget package webapitokenauth(bootstrap).
So for that i have modified authcontroller as per my needs that is i am authenticating user with sql database and returning userid, username, and role for that user in cookies as token.
I check that login method in fiddler its returning 200 ok status code on valid user and 401 for unauthorized user.but when i am trying to call that method via ajax get method in html page +jquery ajax get its returning 401 unauthorized error.
So here in my controller method and javascript code:
Auth controller:
[HttpGet]
[TokenAuthentication(AccessLevel.Anonymous)]
public HttpResponseMessage PostLogin([FromBody]LoginviewModel user)
{
if (user == null || user.UserName == null || user.Password == null)
{
return Error("Please enter username or password.");
}
IUserInfo userinfo = new UserInfo();
var currentuser = userinfo.Checkuser(user.UserName,user.Password);
if (currentuser == null)
{
return Error("Bad username or password.");
}
UserData.Userid = currentuser.UserId;
UserData.username = user.UserName.ToString();
UserData.role = currentuser.Role;
var response = Login(currentuser.UserId,currentuser.Username, UserRole.User);
return response;
}
Index.htm:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$("#Save").click(function () {
var person = new Object();
person.UserName = $('#UserName').val();
person.Password = $('#Password').val();
$.ajax({
url: 'http://localhost:59583/api/auth/login',
type: 'GET',
contentType: 'application/json',
dataType: 'jsonp',
data: JSON.stringify(person),
beforeSend: function (xhr) {
xhr.setRequestHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.setRequestHeader("Access-Control-Allow-Credentials", "true");
},
success: function (response) {
console.log(response);
window.location.href("Portal.htm");
},
error: function (xhr, textStatus, errorThrown) {
console.log(xhr, textStatus, errorThrown);
console.log('Error in Operation');
}
});
});
});
</script>
</head>
<body>
<form id="form1">
Name :- <input type="text" name="UserName" id="UserName" />
Surname:- <input type="password" name="Password" id="Password" />
<input type="button" id="Save" value="Save Data" />
</form>
</body>
</html>