Home
Manage Your Code
Snippet: Forms Authentication (C#)
Title: Forms Authentication Language: C#
Description: Forms Authentication Views: 334
Author: Rajeev Jain Date Added: 12/16/2008
Copy Code  
1protected void btnLogin_Click(object sender, EventArgs e)
2    {
3        AdminUser objAdminUser = new AdminUser();
4        objAdminUser.UserName =txtUserName.Text.Trim();
5        objAdminUser.Password = txtPassword.Text.Trim();
6        if (objAdminUser.AdminLoginUserValidate() != -100)
7        {
8            if (objAdminUser.UserID > 0)
9            {
10                // Create the authentication ticket
11                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
12                    objAdminUser.UserID.ToString(),  // user id
13                    DateTime.Now,               // creation
14                    DateTime.Now.AddMinutes(60),// Expiration
15                    false,						// Persistent
16                    objAdminUser.UserName + "," + objAdminUser.FirstName);	// UserName and Fill Name
17                // Encrypt the ticket.
18                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
19                // Create a cookie and add the encrypted ticket to the cookie as data.
20                HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
21                // Add the cookie to the outgoing cookies collection.
22                Response.Cookies.Add(authCookie);
23                //if there is a previous url to redirect them to 
24                FormsAuthentication.RedirectFromLoginPage(objAdminUser.UserID.ToString(), false);
25                //if (Request.QueryString["ReturnUrl"] == null)
26                //{
27                //    Response.Redirect("Welcome.aspx");
28                //}
29                //else
30                //{
31                //    Response.Redirect(Request.QueryString["ReturnUrl"].ToString());
32                //}
33            }
34        }
35        else
36        {
37            lblMsg.Text = "Invalid username and password.";
38            ModalPopupExtender2.Show();
39        }
40    }
41
42
43In Web.congig 
44
45<authentication mode="Forms">
46			<forms name="SMGR" loginUrl="login.aspx"  defaultUrl="welcome.aspx" timeout="1" protection="All" path="/"/>
47		</authentication>
48
49
50Impliment in page:
51
52bool IsAttribute = false;
53    public void CheckAuthentication()
54    {
55        if (!Context.User.Identity.IsAuthenticated)
56        {
57            string strRedirectURL = Server.UrlEncode(Context.Request.ServerVariables["URL"]);
58            Context.Response.Redirect("Login.aspx?ReturnUrl=" + strRedirectURL);
59        }
60    }
61    protected void Page_Load(object sender, EventArgs e)
62    {
63        CheckAuthentication();
64        
65
66    }