I’m trying to implement authentication using jquery to make an ajax request to a page method that would authenticate a user. This is a basic example I’ve coded below. The actual application is more complex and doesn’t use a page method to handle authentication. The issue is that the isAuthenticated property in the User object is always false. This project is done in vb, but I don’t mind if answers/code are in c#.
Ajax request:
$.ajax({
type: 'POST',
url: 'default.aspx/authenticateUser',
data: "{ username: '" + username + "', password: '" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (d) {
if (d.d == true) {
window.location.href = '/registrants/home.aspx';
}
}
});
Page Method:
<WebMethod()>
Public Shared Function authenticateUser(ByVal username As String, ByVal password As String) As Boolean
If (isAuthenticated(username, password)) Then
Dim ticket As New FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(3), False, "member")
Dim cookie As New HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket))
HttpContext.Current.Request.Cookies.Add(cookie)
Return True
End If
Return False
End Function
It appears the issue is due to my misunderstanding when to use HttpContext.Current.Request vs. HttpContext.Current.Response. Simple mistake. I found the answer here. Once the request is sent to the page method for validation the cookie had to be set using HttpContext.Current.Response and retrieved with HttpContext.Current.Request.