Preferred Language:
Listing 33.21 - ShowLogin.aspx
Illustrates how to authenticate users against ASP.NET membership using client-side code.
The code below has been modified from the code that appears in the book. A server-side authentication
check has been added to the GetSecretMessage() method. Without this additional check, someone could
get the secret message from the server simply by entering the following JavaScript method call into
the browser address bar:
javascript:window.PageMethods.GetSecretMessage(getSecretMessageSuccess, getSecretMessageFail);
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
[System.Web.Services.WebMethod]
public static string GetSecretMessage()
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
throw new Exception("Not Authenticated!");
return "Time is a fish";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Show Login</title>
<script type="text/javascript">
function pageLoad()
{
$addHandler( $get("btnLogin"), "click", login);
}
function login()
{
Sys.Services.AuthenticationService.login
(
$get("txtUserName").value,
$get("txtPassword").value,
false,
null,
null,
loginSuccess,
loginFail
);
}
function loginSuccess(isAuthenticated)
{
if (isAuthenticated)
PageMethods.GetSecretMessage(getSecretMessageSuccess, getSecretMessageFail);
else
alert( "Log in failed" );
}
function loginFail()
{
alert( "Log in failed" );
}
function getSecretMessageSuccess(message)
{
$get("spanMessage").innerHTML = message;
}
function getSecretMessageFail(err)
{
alert( "Could not retrieve secret message: " + err.get_message() );
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager
ID="ScriptManager1"
EnablePageMethods="true"
runat="server" />
<fieldset>
<legend>Login</legend>
<label for="txtUserName">User Name:</label>
<input id="txtUserName" />
<br /><br />
<label for="txtUserName">Password:</label>
<input id="txtPassword" type="password" />
<br /><br />
<input id="btnLogin" type="button" value="Login" />
</fieldset>
The secret message is:
<span id="spanMessage"></span>
</form>
</body>
</html>
ASP.NET 3.5 Unleashed
- Containing almost 2,000 pages of code samples and in-depth explanation of the
ASP.NET 3.5 Framework, ASP.NET 3.5 Unleashed is the most comprehensive book
written on the ASP.NET 3.5 Framework.
ASP.NET 3.5 Unleashed is now available in your local bookstore and online (Published January 7, 2008).
All of the code samples from this book are hosted "live" at this website.
Click here
to view the table of contents and code samples.