Monday, December 5, 2016

User Login in ASP.Net using C# with session


HTML Markup

The HTML markup consists of an ASP.Net Login control for which the OnAuthenticate event handler has been specified. <form id="form1" runat="server"> <asp:Login ID = "Login1" runat = "server" OnAuthenticate= "ValidateUser"></asp:Login> </form>

Namespaces

You will need to import the following namespaces. using System.Data; using System.Configuration; using System.Data.SqlClient; using System.Web.Security; Stored Procedure to Validate the User Credentials The following stored procedure is used to validate the user credentials, this stored procedure first checks whether the username and password are correct else returns -1. If the username and password are correct but the user has not been activated then the code returned is -2. If the username and password are correct and the user account has been activated then UserId of the user is returned by the stored procedure. 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 Validating the User Credentials The below event handler gets called when the Log In button is clicked. Here the Username and Password entered by the user is passed to the stored procedure and its status is captured and if the value is not -1 (Username or password incorrect) or -2 (Account not activated) then the user is redirected to the Home page using FormsAuthentication RedirectFromLoginPage method. 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; } } } Home Page After successful login user will be redirected to this page. HTML Markup In this page I have made use of ASP.Net LoginName control to display the name of the Logged In user and LoginStatus control to allow user Logout. <div> Welcome <asp:LoginName ID="LoginName1" runat="server" Font-Bold = "true" /> <br /> <br /> <asp:LoginStatus ID="LoginStatus1" runat="server" /> </div> Namespaces You will need to import the following namespaces. using System.Web.Security; Verify whether User has Logged In Inside the Page Load event, first we verify whether the User is authenticated using the IsAuthenticated property. If the user is not authenticated then he is redirected back to the Login page using FormsAuthentication RedirectToLoginPage method. protected void Page_Load(object sender, EventArgs e) { if (!this.Page.User.Identity.IsAuthenticated) { FormsAuthentication.RedirectToLoginPage(); } } Web.Config Configuration You will need to add the following configuration in the Web.Config file in the <system.web> section. <authentication mode="Forms"> <formsdefaultUrl="~/Home.aspx" loginUrl="~/Login.aspx" slidingExpiration="true" timeout="2880"></forms> </authentication>

No comments:

Post a Comment