How to secure my login page

前端 未结 2 1855
青春惊慌失措
青春惊慌失措 2020-12-31 22:14

I have a login.html webpage that lets user enter his username and password. When he clicks on submit I collect the entered value using Javascript and then make a Ajax POST C

相关标签:
2条回答
  • 2020-12-31 22:40

    This really belongs on codereview.stackexchange.com, but I'll give it a shot anyway.

    Firstly, I'd add a csrf token to your form to stop those types of attacks.

    //the most simple type of csrf token
    if (!isset($_SESSION['token'])):
        $token = md5(uniqid(rand(), TRUE));
        $_SESSION['token'] = $token;
    else:
        $token = $_SESSION['token'];
    endif;
    

    Then in your form, include a hidden input field:

    <input type="hidden" name="token" id="token" value="<?php echo $token; ?>"/>
    

    Then in your ajax, add the token.

    var usrnm = $('#usrnm').val();
    var pswdlogin = $('#pswdlogin').val();
    var token = $('#token').val();
    
    {
        usrnm: usrnm,
        pswdlogin: pswdlogin,
        token: token
    }
    

    Then in your php, let's stop the undefined index errors on access of that page directly.

    $usrnm_original = isset($_POST['usrnm'])?$_POST['usrnm']:false;
    $pswdlogin_original = isset($_POST['pswdlogin'])?$_POST['pswdlogin']:false;
    $token = isset($_POST['token'])$_POST['token']:false;
    

    Then we need to check if the token that was passed is the same as our token

    if(!$_SESSION['token'] == $token):
        die('CSRF Attacks are not allowed.');
    endif;
    

    Then we need to stop using mysqli_query when accepting user data, even if sanitizing with mysqli_real_escape_string and instead use prepared statements. Also, procedural style code makes me cry, so we'll be changing that. Furthermore, let's return an array with a status and a message, so it's easier to handle the error and success reporting.

    $ret = array();
    $mysqli = new mysqli("localhost", "cSDEqLj", "4GFU7vT", "dbname");
    
    if($sql = $mysqli->prepare('SELECT * FROM registration WHERE email = ? and password = ?')):
        $sql->bind_param('ss', $usrnm_original, $pswd_original);
    
        if($sql->execute()):
    
            $sql->fetch();
    
            if($sql->num_rows > 0):
                $ret['status'] = true;
                $ret['msg'] = 'You have successfully logged in! Redirecting you now';
            else:
                $ret['status'] = false;
                $ret['msg'] = 'The credentials supplied were incorrect. Please try again';
            endif;
        endif;
        $sql->close();
        return json_encode($ret);
    endif;
    

    Now we need to modify your post function.

    $.post("http://xyz/mobile/php/logmein.php",
    {
      usrnm: usrnm,
      pswdlogin: pswdlogin,
      token:token
    },
    function(data) {
    
      if (data.status == true) {
    
        window.open("http://xyz/mobile/home.html?email=" + usrnm + "", "_parent");
    
      } else {
        alert(data.msg);
        $('#loginstatus').text(data.msg);
      }
    }, 'json');
    

    Finally, and most importantly, you have a plain text method of passwords being used, which makes no sense from a security perspective. This is precisely how you get hacked. Instead, you should be using at least the sha256 hashing method. Change how the passwords are stored in the database to use sha256 then make a comparison by passing that into the SQL selector, example:

    $pswdlogin_original = isset($_POST['pswdlogin'])? hash('sha256', $_POST['pswdlogin']):false;
    

    And when saved in the database, the password will look like fcec91509759ad995c2cd14bcb26b2720993faf61c29d379b270d442d92290eb for instance.

    My answer has been for clarity sake, but in reality, you shouldn't even be reinventing things. There's plenty of applications and framework's out there that have placed countless hours into securing their authentication systems. I would recommend having a look into all of these, as they'll help build your core programming skills and teach fundamental OOP practices

    • Lararvel 4.x
    • Zend 2
    • Phalcon
    • Yi

    Hopefully this has been helpful.

    0 讨论(0)
  • 2020-12-31 22:42

    First of all, if you want "top" security you should use HTTPS with a valid certificate, otherwise any attacker may be able to create a Man in the middle attack and intercept your data (I guess this is your main concern). Doing the HTTPS on the login page only is meaningless as the same attacker could do a Session Hijacking attack and impersonate other users without knowing the password.

    Be aware that there is no difference of using AJAX or an HTML form, the data is sent though the wire in the same way.

    If you don't want to spent more resources (usually HTTPS cerficates costs money), you can go the "not that good route": pass a hashed version of the password, but this has its downsides too (if you don't hash at server side, then the password becomes the hash itself...)

    As adviced, don't try to reinvent the wheel, try using a well known framework like Laravel, or one smaller like Slim or Silex, it might be easier to migrate your code to them.

    At the end you must ask yourself, what is the worst case scenario if some user gets access to another account? If you're deploying a trivial app with no personal data, maybe your current solution is good enough on the other hand if you're dealing with sensitive information you must pay good attention securing your website.

    Further reading:

    • About session hijacking
    • About Man In the Middle
    • Storing passwords "the good way" (TM)
    0 讨论(0)
提交回复
热议问题