Friday, February 20, 2009

Form Authentication

Login Through Cookies
Detecting ASP.NET Session Timeouts

            
                
                
            
        

We have to set the value to the attribute path="/" in forms tag. Then only a common authentication works for both the browsers (Internet Explorer and Firefox.)
I.e. we logged in IE and open the page in Firefox it once again ask to logon. To over come this gives the path.

The place the cookies are stored in windows XP.
The default location for Internet Explorer
C:\Documents and Settings\\Cookies

If you set form authentication it give the user name that you gave in Login control other wise it took as windows authentication and gave windows user name.
string webUsername = HttpContext.Current.User.Identity.Name;

    protected void LoginAuthenticate(object sender, AuthenticateEventArgs e)
    {
        //if username and password given by the enduser is available in the
        //database then we can authenticate the user by providing

        e.Authenticated = true;
        AuthenticateUser("UserName");
    }

    protected void AuthenticateUser(string userName)
    {
        /*Providing the FormsAuthenticationTicket "Ticket" to the authenticated
        user which contains version, username, entry datetime and expire date time,
        userdata and cookie path*/
        FormsAuthentication.Initialize();
        FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket
        (1, userName.Trim(), DateTime.Now, DateTime.Now.AddMinutes(90),
        true, userName.Trim() + "," + Page.ClientID,
        FormsAuthentication.FormsCookiePath);

        //encrypt the ticket and assign it into the string variable "hash"
        string hash = FormsAuthentication.Encrypt(Ticket);

        /*FormsAuthentication.FormsCookieName --> This is the name
        that we gave in web.config file*/

        HttpCookie Cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
        Response.Cookies.Clear();

        /*checking whether the cookie is constant,
        If constant then expires the cookie based on the expiration
        time of user specified in ticket
        */
        if (Ticket.IsPersistent)
        {
            Cookie.Expires = Ticket.Expiration;
            Response.Cookies.Add(Cookie);
        }
    }

    //When writing a cookie, use Response but reading may depend on your situation. 
    //Normally, you read from Request but if your application is attempting 
    //to get a cookie that has just been written or updated and the round trip 
    //to the browser has not occured, you may need to read it form Response.

    public void WriteCookie(string name, string value)
    {
        HttpCookie cookie = new HttpCookie(name, value);
        HttpContext.Current.Response.Cookies.Set(cookie);
    }

    public string ReadCookie(string name)
    {
        string[] CookiesKeys = HttpContext.Current.Response.Cookies.AllKeys;
        if (((IList)CookiesKeys).Contains(name))
        {
            HttpCookie cookie = HttpContext.Current.Response.Cookies[name];
            if (cookie != null) return cookie[name];
        }

        CookiesKeys = HttpContext.Current.Request.Cookies.AllKeys;
        if (((IList)CookiesKeys).Contains(name))
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
            if (cookie != null) return cookie[name];
        }
        return null;
    }

    //Update Cookie 
    private void UpdateCookie()
    {
        // If the request cookie exists, copy it to the response.
        // Otherwise create a response cookie.
        HttpCookie cookie = Request.Cookies["theCookie"];
        if (cookie == null)
        {
            Response.Cookies.Set(new HttpCookie("theCookie", "SomeValue"));
        }
        else
        {
            Response.Cookies.Set(cookie);
            // Add the expiration date. 
            cookie.Expires = DateTime.Now.AddYears(30);
            // Change the cookie's value 
            cookie.Value = "NewValue";
        }
    }

    private string GetCurrentCookieValue()
    {
        string currentCookieValue = null;
        // Response.Cookies always has the latest values
        if (Request.Browser.Cookies)
        {
            HttpCookie cookie = Request.Cookies["theCookie"];
            if (cookie != null) currentCookieValue = cookie.Value;
        }
        return currentCookieValue;
    }

    protected void ibtnLogedOut_Click(object sender, EventArgs e)
    {
        Session.RemoveAll();
        Session.Clear();
        //Removes the FormsAuthentication ticket from the server
        FormsAuthentication.SignOut();

        #region Removers Cookie When User Log Off
        //Clear cookie when user Logout 
        Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
        #endregion

        ibtnLogin.Visible = true;
        ibtnLogOut.Visible = false;

        Response.Redirect("~/Home.aspx");
    }
Add the below code in Global.asax
    //Code that runs on application startup
    protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.User != null)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (HttpContext.Current.User.Identity is FormsIdentity)
                {
                    FormsIdentity FID = (FormsIdentity)HttpContext.Current.User.Identity;
                    FormsAuthenticationTicket Ticket = FID.Ticket;

                    //Get the stored user-data, in this case, Page Client ID and UserName
                    string userData = Ticket.UserData;
                    string[] roles = userData.Split(',');
                    HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(FID, roles);
                }
            }
        }
    }
Set the cookie expiration time by giving the session time out
    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        bool isPersistent = this.Login1.RememberMeSet;
        string username = this.Login1.UserName;
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
            (
                1,//Version
                username,
                DateTime.Now,// issueDate
                GetExpirationTime(),// expiration
                isPersistent,// isPersistent
                Guid.NewGuid().ToString("N"), //roles or userData
                FormsAuthentication.FormsCookiePath // cookiePath
            );

        // Encrypt the ticket.
        string encryptedTicket = FormsAuthentication.Encrypt(ticket);

        // Create the cookie.
        this.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket));

        Session["UserName"] = username;

        // Redirect back to original URL.
        this.Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent));
    }

    private DateTime GetExpirationTime()
    {
        double minutes = 0;
        TimeSpan obj;
        minutes = ((System.Web.Configuration.AuthenticationSection)System.Configuration.ConfigurationManager.GetSection("system.web/authentication")).Forms.Timeout.Minutes;
        obj = TimeSpan.FromMinutes(minutes);
        return DateTime.Now.AddMinutes(obj.Minutes);
    }
Note
//Clear cookie when user Logout 
Response.Cookies.Remove(FormsAuthentication.FormsCookieName); 
//Removes the FormsAuthentication ticket from the server 
FormsAuthentication.SignOut(); 
//Note If you set form authentication it give the user name that you gave in Login control. 
//other wise it took as windows authentication and gave windows user name 
//string webUsername = HttpContext.Current.User.Identity.Name; 
//==================================================================== 
//Get Windowns userName 
string str = Request.ServerVariables["LOGON_USER"];
Brute force protect your websites

No comments: