I worked on this site over the summer at an office, I'm now back on christmas break, and will work again this summer. With the help of many people online I got the following code to work. But now, it doesn't work. As far as I know, the code SHOULD still be the same. I am using VS2005 instead of VWD beta, and the 2.0 framework instead of the beta version.
Outline of what the below code should do:
Take user login information, pass it to storedprocedure DBAuthenticate, if valid user, then execute another query to retrieve role info for forms authentication and store it in the authentication ticket. As well as pause for every missed attempt.
What happens:
The login page will load correctly, but when you hit the submit button i get the following error.
"Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation."
MASTERPAGE(Anonymous.master):
<%@ Master Language="VB" CodeFile="Anonymous.master.vb" Inherits="Anonymous" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="width: 740px; height: 720;" border="1">
<tr>
<td colspan="3" style="height: 87px">
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/top_data/background.jpg" /></td>
</tr>
<tr>
<td colspan="3" style="height: 236px">
<asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
</asp:contentplaceholder>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Login.aspx:
<%@ Page Language="VB" MasterPageFile="~/Anonymous.master"
AutoEventWireup="false"
CodeFile="Login.aspx.vb"
Inherits="_Default"
EnableEventValidation="true"
title="Untitled Page" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Threading" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script runat="server">
Dim conMyData As SqlConnection
Dim conUserData As SqlConnection
Dim cmdSelect As SqlCommand
Dim cmdSelectRoles As SqlCommand
Dim parmReturnValue As SqlParameter
Dim intResult As Integer
Dim strLinkPath As String
Dim objTicket As FormsAuthenticationTicket
Dim objCookie As HttpCookie
Dim strReturnURL As String
Sub Button_Click(ByVal a As Object, ByVal e As EventArgs)
If IsValid Then
'load stored procedure DBAuthenticate
If DBAuthenticate(txtUsername.Text, txtPassword.Text) > 0 Then
'run query to get user role for forms based authentication
Dim conRoles As SqlConnection
Dim cmdSelectRoles As SqlCommand
Dim dtrRoles As String
conRoles = New SqlConnection("Server=INTRANET;uid=sa;database=safety_training")
conRoles.Open()
cmdSelectRoles = New SqlCommand("SELECT r.role_name FROM dbo.Roles r WHERE r.role_id IN (SELECT ui.role_id FROM dbo.User_Info ui WHERE ui.user_name=@username AND ui.password=@password)", conRoles)
cmdSelectRoles.Parameters.AddWithValue("@username", txtUsername.Text)
cmdSelectRoles.Parameters.AddWithValue("@password", txtPassword.Text)
dtrRoles = cmdSelectRoles.ExecuteScalar
'run query to get users company
Dim conCompany As SqlConnection
Dim cmdSelectCompany As SqlCommand
Dim dtrCompany As String
conCompany = New SqlConnection("Server=INTRANET;uid=sa;database=safety_training")
conCompany.Open()
cmdSelectCompany = New SqlCommand("SELECT ui.company_id FROM dbo.User_Info ui WHERE ui.user_name=@username", conCompany)
cmdSelectCompany.Parameters.AddWithValue("@username", txtUsername.Text)
dtrCompany = cmdSelectCompany.ExecuteScalar
'create authentication ticket
objTicket = New FormsAuthenticationTicket(2, txtUsername.Text, DateTime.Now, DateTime.Now.AddMinutes(30), False, dtrRoles)
conRoles.Close()
conCompany.Close()
'create cookie Company
Response.Cookies("Company").Value = dtrCompany
'create cookie UserName
Response.Cookies("UserName").Value = txtUsername.Text
objCookie = New HttpCookie(".ASPXAUTH")
objCookie.Value = FormsAuthentication.Encrypt(objTicket)
Response.Cookies.Add(objCookie)
strReturnURL = Request.Params("ReturnURL")
If strReturnURL <> Nothing Then
'returns user to previous page if greater authorization was required
Response.Redirect(strReturnURL)
Else
'forwards user after login
Response.Redirect("Default.aspx")
End If
End If
End If
End Sub
'check failed login attempt count and if greater than 3 pauses for 2 hours
Sub Page_Load()
Dim objCounter As Object = Session("counter")
If Session("counter") > 3 Then
Thread.Sleep(7200000)
Response.Redirect("anonymous/deny.aspx")
End If
End Sub
'stored procedure, returns 1 if successful login, -1 it not
Function DBAuthenticate(ByVal strUsername As String, ByVal strPassword As String) As Integer
conMyData = New SqlConnection("Server=INTRANET;UID=sa;Database=safety_training")
cmdSelect = New SqlCommand("DBAuthenticate", conMyData)
cmdSelect.CommandType = CommandType.StoredProcedure
parmReturnValue = cmdSelect.Parameters.Add("RETURN_VALUE", SqlDbType.Int)
parmReturnValue.Direction = ParameterDirection.ReturnValue
cmdSelect.Parameters.AddWithValue("@Username", strUsername)
cmdSelect.Parameters.AddWithValue("@Password", strPassword)
conMyData.Open()
cmdSelect.ExecuteNonQuery()
intResult = cmdSelect.Parameters("RETURN_VALUE").Value
conMyData.Close()
'if unsuccessful login display message and increase failed attempt count by 1 then
'pauses for 10, then 20, then 30 seconds if user keeps failign
If intResult = -1 Then
lblMessage.Text = "Your Username or Password is incorrect. Please try again."
Dim objCounter As Object = Session("counter")
If objCounter Is Nothing Then objCounter = 0
Session("counter") = CInt(objCounter) + 1
Thread.Sleep(10000 * (CInt(objCounter)))
End If
Return intResult
End Function
</script>
<form id="Form1" action="Login.aspx" >
<table style="width: 41%; border-right: #b5c7de 1px solid; border-top: #b5c7de 1px solid; border-left: #b5c7de 1px solid; border-bottom: #b5c7de 1px solid; height: 1px;">
<tr align="center" valign="top">
<td bgcolor="#eff3fb" style="text-align: center; width: 843px; height: 175px;">
<table>
<tr>
<td colspan="2"
style="text-align: center">
<strong><span style="font-weight: bold;
color: black;
background-color: transparent; font-family: Verdana;">Log In</span></strong></td>
</tr>
<tr align="center">
<td colspan="2">
<asp:Label
ID="lblMessage"
ForeColor="Red"
Runat="server" /></td>
</tr>
<tr valign="top">
<td style="width: 85px">
<asp:Label ID="UserNameLabel"
runat="server" Font-Names="Verdana" Font-Size="0.8em">User Name:</asp:Label>
</td>
<td style="width: 173px">
<asp:TextBox ID="txtUsername"
runat="server"
Width="160px" TabIndex="1" /><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server"
ControlToValidate="txtUsername"
Text="You must enter a User Name." Width="186px" EnableViewState="False" Font-Names="Verdana" Font-Size="0.7em" /></td>
</tr>
<tr valign="top">
<td style="width: 85px">
<asp:Label ID="PasswordLabel"
runat="server" Font-Names="Verdana" Font-Size="0.8em">Password:</asp:Label>
</td>
<td style="width: 173px">
<asp:TextBox ID="txtPassword"
runat="server"
TextMode="Password"
Width="160px" TabIndex="2" /><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2"
runat="server"
ControlToValidate="txtPassword"
Text="You must enter a Password." Width="235px" EnableViewState="False" Font-Names="Verdana" Font-Size="0.7em" /></td>
</tr>
<tr align="center">
<td colspan="2" style="height: 32px; text-align: right">
<asp:Button ID="Button1"
runat="server"
BackColor="White"
BorderColor="#507CD1"
BorderStyle="Solid"
BorderWidth="1px"
OnClick="Button_Click"
Font-Names="Verdana"
Font-Size="0.8em"
ForeColor="#284E98"
Text="Log In" TabIndex="3" /></td>
</tr>
</table>
<span style="font-size: 0.8em; color: red"></span></td>
</tr>
</table>
</form>
</asp:Content>
Global.asax:
<%@ Application Language="VB" %>
<script runat="server">
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
If Not (HttpContext.Current.User Is Nothing) Then
If HttpContext.Current.User.Identity.IsAuthenticated Then
If TypeOf HttpContext.Current.User.Identity Is FormsIdentity Then
Dim id As FormsIdentity = CType(HttpContext.Current.User.Identity, FormsIdentity)
Dim ticket As FormsAuthenticationTicket = id.Ticket
Dim userData As String = ticket.UserData
Dim roles As String() = userData.Split(",")
HttpContext.Current.User = New System.Security.Principal.GenericPrincipal(id, roles)
End If
End If
End If
End Sub
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application startup
End Sub
Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application shutdown
End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
End Sub
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when a new session is started
End Sub
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when a session ends.
' Note: The Session_End event is raised only when the sessionstate mode
' is set to InProc in the Web.config file. If session mode is set to StateServer
' or SQLServer, the event is not raised.
End Sub
</script>
Web.Config:
<?xml version="1.0"?>
<!-- Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
<!-- ASP.NET connection string to connect to
Microsoft SQL Server INTRANET, database Safety_Training -->
<connectionStrings>
<add name="Safety_TrainingConnectionString"
connectionString="Data Source=INTRANET; Initial Catalog=Safety_Training; User ID=sa"
providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<!-- Authorization section sets access for anonymous users throughout site -->
<authorization>
<deny users="?"/>
</authorization>
<!-- Sets Authentication Method for site, Forms based and denies access
to folder (root) for non authenticated users
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user -->
<authentication mode="Forms">
<forms name=".ASPXAUTH"
loginUrl="login.aspx"
protection="All"
path="/"
timeout="5"/>
</authentication>
<!-- The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors> -->
<customErrors mode="Off"/>
<!-- Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development -->
<compilation debug="true"/>
<!-- Defines the sitemap provider for the navigation controls -->
</system.web>
<appSettings/>
</configuration>