Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Other Discussions
  3. The Weird and The Wonderful
  4. how not to check a login [modified]

how not to check a login [modified]

Scheduled Pinned Locked Moved The Weird and The Wonderful
announcementsecurityregexhelp
17 Posts 11 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • I icewolf_snowfire

    when you use a SqlDataReader, you always have to check if it actually contains any data with reader.HasRows if it doesn't have data, like in this case if the username is not in the database, it throws an InvalidOperationException "Invalid attempt to read when no data is present" what's happening is the person who wrote this, didn't understand what was causing the exception, so he just handled in with a try catch, rather than fixing the actual problem.

    L Offline
    L Offline
    leppie
    wrote on last edited by
    #8

    icewolf_snowfire wrote:

    reader.HasRows

    Wouldn't if (reader.Read()) { ... } be ok too?

    xacc.ide
    IronScheme - 1.0 beta 3 - out now!
    ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

    I M 2 Replies Last reply
    0
    • S supercat9

      I'm not sure what's worse, that a professional development company has people who think this is how you use exceptions, or that my company actually paid money for this code Unsure I love the way they put database errors in the message to the user, and identify which they got wrong, the username or the password.Mad In many situations, it's entirely reasonable to distinguish a bad username from a bad password. User names are generally not secure, and legitimate users may not always remember which variation of their username they used at a particular site. Having a login routine throw an exception for user-not-found is not the best, but if a custom exception were used for that purpose, it wouldn't be totally horrible. The only really horrible thing I see is the munging of the exception message. BTW, one feature I'd like to see on a web site would be an option for users to specify a string that should be displayed on an unsuccessful login attempt, with the instruction that the string should contain something recognizable, but should not contain any security-related information. That would allow someone who mistakenly tries to log in with someone else's username to immediately realize their mistake.

      R Offline
      R Offline
      Russell Jones
      wrote on last edited by
      #9

      It would also be nice if sites told you what the rules for passwords were so that you knew which passwords you were likely to have used on a given site. Often I've had to try to create a new account to find out what the rules are for a site so I can login again. Life was so much easier before websites started getting themselves removed from BugMeNot!

      S 1 Reply Last reply
      0
      • I icewolf_snowfire

        this is one of the many gems I'm finding (and fixing) in some third party produced code:

        protected void btnLogin_Click(Object s, EventArgs e)
        {
        bool loginOK = false;
        try
        {
        loginOK = Account.LoginUser(Page, txtUserName.Text, txtPassword.Text);
        }
        catch (Exception ex)
        {
        string error = string.Empty;
        if (ex.Message == "Invalid attempt to read when no data is present.")
        {
        error = "Username not found.";
        }
        else
        {
        error = ex.Message;
        }
        lblMessage.Text = error;
        return;
        }

        	if (loginOK == true)
        	{
        		Response.Redirect("~/Default.aspx");
        	}
        	else
        	{
        		**lblMessage.Text = "Password does not match.";**
        	}
        }
        

        public static bool LoginUser(Page page, string uname, string pass)
        {
        bool passwordVerified = false;

        		try
        		{
        			passwordVerified = AccountDB.CheckPassword(uname, pass);
        		}
        		catch (Exception ex)
        		{
        			throw;
        		}
        
        		if (passwordVerified == true)
        		{
        			//string roles = "Manager" + "|" + "Administrator";
        			string roles = "JobSeeker";
        
        			// Create the authentication ticket
        			FormsAuthenticationTicket authTicket = new
        				FormsAuthenticationTicket(1,  // version
        				uname,      // user name
        				DateTime.Now,	// creation
        				DateTime.Now.AddMinutes(60),// Expiration
        				false,	// Persistent
        				roles	// User data
        										 );
        
        			string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
        
        			HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
        			page.Response.Cookies.Add(authCookie);
        
        			// Update login date to now
        			int userID = AccountDB.GetUserIDByUsername(uname);
        			AccountDB.UpdateLoginDate(userID, DateTime.Now);
        
        			return true;
        		}
        		else
        		{
        			return false;
        		}
        	}
        

        public static bool CheckPassword(string username, string password)
        {
        bool passwordMatch = false;
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand("CheckPassword", conn);
        cmd.CommandType = CommandType.StoredProcedure;

        		SqlParameter sqlParam = cmd.Parameters.Add("@userName", SqlDbType.VarChar, 255);
        		sqlParam.Value = username;
        		try
        		{
        			conn.Open();
        			**SqlDataReader reader = cmd.ExecuteReader();
        			reader.Read();**
        			string dbPasswordHash = reader.GetString(0);
        			string salt = reader.GetString(1);
        			reader.Close();
        
        			// Generat
        
        J Offline
        J Offline
        Jammer 0
        wrote on last edited by
        #10

        I've seen the exact same crap from a third party 'development company' my employer has recently stopped using. I ended up submitting report after report on how bad their code was ... finally got listened to and we promptly dumped them.

        Jammer My Blog | Article(s)

        1 Reply Last reply
        0
        • I icewolf_snowfire

          this is one of the many gems I'm finding (and fixing) in some third party produced code:

          protected void btnLogin_Click(Object s, EventArgs e)
          {
          bool loginOK = false;
          try
          {
          loginOK = Account.LoginUser(Page, txtUserName.Text, txtPassword.Text);
          }
          catch (Exception ex)
          {
          string error = string.Empty;
          if (ex.Message == "Invalid attempt to read when no data is present.")
          {
          error = "Username not found.";
          }
          else
          {
          error = ex.Message;
          }
          lblMessage.Text = error;
          return;
          }

          	if (loginOK == true)
          	{
          		Response.Redirect("~/Default.aspx");
          	}
          	else
          	{
          		**lblMessage.Text = "Password does not match.";**
          	}
          }
          

          public static bool LoginUser(Page page, string uname, string pass)
          {
          bool passwordVerified = false;

          		try
          		{
          			passwordVerified = AccountDB.CheckPassword(uname, pass);
          		}
          		catch (Exception ex)
          		{
          			throw;
          		}
          
          		if (passwordVerified == true)
          		{
          			//string roles = "Manager" + "|" + "Administrator";
          			string roles = "JobSeeker";
          
          			// Create the authentication ticket
          			FormsAuthenticationTicket authTicket = new
          				FormsAuthenticationTicket(1,  // version
          				uname,      // user name
          				DateTime.Now,	// creation
          				DateTime.Now.AddMinutes(60),// Expiration
          				false,	// Persistent
          				roles	// User data
          										 );
          
          			string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
          
          			HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
          			page.Response.Cookies.Add(authCookie);
          
          			// Update login date to now
          			int userID = AccountDB.GetUserIDByUsername(uname);
          			AccountDB.UpdateLoginDate(userID, DateTime.Now);
          
          			return true;
          		}
          		else
          		{
          			return false;
          		}
          	}
          

          public static bool CheckPassword(string username, string password)
          {
          bool passwordMatch = false;
          SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
          SqlCommand cmd = new SqlCommand("CheckPassword", conn);
          cmd.CommandType = CommandType.StoredProcedure;

          		SqlParameter sqlParam = cmd.Parameters.Add("@userName", SqlDbType.VarChar, 255);
          		sqlParam.Value = username;
          		try
          		{
          			conn.Open();
          			**SqlDataReader reader = cmd.ExecuteReader();
          			reader.Read();**
          			string dbPasswordHash = reader.GetString(0);
          			string salt = reader.GetString(1);
          			reader.Close();
          
          			// Generat
          
          P Offline
          P Offline
          PaPaSEK
          wrote on last edited by
          #11

          I don't think these are the bad Idea or junk or crap etc. whatever you called it. It just the way of programming. And it the way the programmer want it to be. One Algorithm can be done in many way. So If you think you can write a better one, You should not shout into their face an say something Like "Your code is bad. I found this junk in your code. I am the best." Impressive Huh!? What you should do is give them a suggestion, Though it free :laugh:

          T 1 Reply Last reply
          0
          • R Russell Jones

            It would also be nice if sites told you what the rules for passwords were so that you knew which passwords you were likely to have used on a given site. Often I've had to try to create a new account to find out what the rules are for a site so I can login again. Life was so much easier before websites started getting themselves removed from BugMeNot!

            S Offline
            S Offline
            supercat9
            wrote on last edited by
            #12

            Russell Jones wrote:

            It would also be nice if sites told you what the rules for passwords were so that you knew which passwords you were likely to have used on a given site. Often I've had to try to create a new account to find out what the rules are for a site so I can login again. Life was so much easier before websites started getting themselves removed from BugMeNot!

            No kidding. If a site requires passwords to be precisely eight characters, how is it any less secure to remind people of that at the login screen than after they create a new account? (Of course, requiring that passwords be exactly eight characters seems a dumb design anyway--even if the system only had space to store eight bytes, and policy factors dictated an eight-character minimum, the system should easily be able to hash a password of arbitrary length into an eight-byte digest or--failing that--just take the first eight bytes of the password and ignore the rest).

            1 Reply Last reply
            0
            • L leppie

              icewolf_snowfire wrote:

              reader.HasRows

              Wouldn't if (reader.Read()) { ... } be ok too?

              xacc.ide
              IronScheme - 1.0 beta 3 - out now!
              ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

              I Offline
              I Offline
              icewolf_snowfire
              wrote on last edited by
              #13

              you're right it would, I didn't realize that was there. (and neither did they) it would be less lines of code, so slightly more efficient?

              L 1 Reply Last reply
              0
              • P PaPaSEK

                I don't think these are the bad Idea or junk or crap etc. whatever you called it. It just the way of programming. And it the way the programmer want it to be. One Algorithm can be done in many way. So If you think you can write a better one, You should not shout into their face an say something Like "Your code is bad. I found this junk in your code. I am the best." Impressive Huh!? What you should do is give them a suggestion, Though it free :laugh:

                T Offline
                T Offline
                Tristan Rhodes
                wrote on last edited by
                #14

                Well... you can lead a horse to water...

                ------------------------------- Carrier Bags - 21st Century Tumbleweed.

                V 1 Reply Last reply
                0
                • L leppie

                  icewolf_snowfire wrote:

                  reader.HasRows

                  Wouldn't if (reader.Read()) { ... } be ok too?

                  xacc.ide
                  IronScheme - 1.0 beta 3 - out now!
                  ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

                  M Offline
                  M Offline
                  MarkB777
                  wrote on last edited by
                  #15

                  I've always used while (reader.Read()) { ... } which does the trick.

                  Mark Brock "We're definitely not going to make a G or a PG version of this. It's not PillowfightCraft." -- Chris Metzen Click here to view my blog

                  1 Reply Last reply
                  0
                  • I icewolf_snowfire

                    you're right it would, I didn't realize that was there. (and neither did they) it would be less lines of code, so slightly more efficient?

                    L Offline
                    L Offline
                    Lutoslaw
                    wrote on last edited by
                    #16

                    icewolf_snowfire wrote:

                    it would be less lines of code, so slightly more efficient?

                    lol.

                    Greetings - Jacek

                    1 Reply Last reply
                    0
                    • T Tristan Rhodes

                      Well... you can lead a horse to water...

                      ------------------------------- Carrier Bags - 21st Century Tumbleweed.

                      V Offline
                      V Offline
                      Vozzie2
                      wrote on last edited by
                      #17

                      And remind him he was drinking poison...

                      It feels good to learn and achieve

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups