Hi abelgebray,
I have created one sample please check this.
SQL
CREATE PROCEDURE [dbo].[Validate_User]
@Username NVARCHAR(20),
@Password NVARCHAR(20)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @UserId INT, @LastLoginDate DATETIME
SELECT @UserId = UserId, @LastLoginDate = LastLoginDate
FROM Users WHERE Username = @Username AND [Password] = @Password
IF @UserId IS NOT NULL
BEGIN
IF NOT EXISTS(SELECT UserId FROM UserActivation WHERE UserId = @UserId)
BEGIN
UPDATE Users
SET LastLoginDate = GETDATE()
WHERE UserId = @UserId
SELECT @UserId [UserId] -- User Valid
END
ELSE
BEGIN
SELECT -2 -- User not activated.
END
END
ELSE
BEGIN
SELECT -1 -- User invalid.
END
END
HTML of Login.aspx
<asp:Login ID="Login1" runat="server" OnAuthenticate="ValidateUser">
</asp:Login>
Code
protected void ValidateUser(object sender, EventArgs e)
{
int userId = 0;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Validate_User"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username", Login1.UserName);
cmd.Parameters.AddWithValue("@Password", Login1.Password);
cmd.Connection = con;
con.Open();
userId = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
switch (userId)
{
case -1:
Login1.FailureText = "Username and/or password is incorrect.";
break;
case -2:
Login1.FailureText = "Account has not been activated.";
break;
default:
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet);
break;
}
}
Session["name"] = Login1.UserName;
}
HTML of Home.aspx
<div>
<table>
<tr>
<td>
Welcome
<asp:LoginName ID="LoginName1" runat="server" Font-Bold="true" />
</td>
<td>
<asp:LoginStatus ID="LoginStatus1" runat="server" />
</td>
</tr>
</table>
</div>
<div>
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="False" DataKeyNames="UserId"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="Username" HeaderText="Username" SortExpression="Username" />
<asp:BoundField DataField="Password" HeaderText="Password" SortExpression="Password" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:LoginDBConnectionString %>"
SelectCommand="SELECT * FROM [Users] WHERE ([Username] = @Username)">
<SelectParameters>
<asp:SessionParameter Name="Username" SessionField="name" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</div>
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.User.Identity.IsAuthenticated)
{
FormsAuthentication.RedirectToLoginPage();
}
}
You will need to add the following configuration in the Web.Config file in the <system.web> section.
<authentication mode="Forms">
<forms defaultUrl="~/Home.aspx" loginUrl="~/Login.aspx" slidingExpiration="true" timeout="2880"></forms>
</authentication>