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>
Need ASP.NET and Visual Studio 2008 Training?
- Learn ASP.NET 3.5 from Stephen Walther, author of ASP.NET 3.5 Unleashed.
We've provided ASP.NET training for NASA, Lockheed Martin, the National Science Foundation, Verizon,
Boeing, the US House of Representatives, Kaiser, Petco, Mary Kay, and Microsoft.
Why not your company?
-
Receive a four day, hands-on, intensive workshop.
-
We fly to you, anywhere in the world.
-
We can bring our own laptops.
To learn more, visit the
Superexpert Training website.