Checking if user has changed cookie value, manually

前端 未结 4 1344
礼貌的吻别
礼貌的吻别 2021-02-06 02:52

I am busy with a login system for my project.

Just for an extra step to the security.. How can I check/detect if a user has manually changed a cookie value?

Is t

相关标签:
4条回答
  • 2021-02-06 03:32

    If you have to handle such sensitive information, I would suggest you not store it in user cookies. Instead use sessions to store such values as the user will not be able to tamper with such values.

    0 讨论(0)
  • 2021-02-06 03:32

    Add a second variable to your cookie, which is unique to the first value.

    On Page_Load compare the two values to the database.

    If they do not match a record, then delete the cookie.

    0 讨论(0)
  • 2021-02-06 03:47

    You could append a digital signature to the cookie value and check the signature when you read it back. That way, if the cookie value is tampered with it will be very apparent.

    private string sign(string hashStr, byte[] secret) 
    {
        // Compute the signature hash
        HMACSHA1 mac = new HMACSHA1(secret);
        byte[] hashBytes = Encoding.UTF8.GetBytes(hashStr);
        mac.TransformFinalBlock(hashBytes, 0, hashBytes.Length);
        byte[] hashData = mac.Hash;
    
        // Encode the hash in Base64.
        string hashOut = Convert.ToBase64String(hashData);
    
        return hashOut;
    }
    

    Edit: Fixed the encoder so it's explicitly UTF-8.

    As usual, you should also be sure to add some salt to your string before calling this, see: Secure hash and salt for PHP passwords

    0 讨论(0)
  • 2021-02-06 03:47

    Why don't you encrypt the cookie value. That way it is tough for the user to actually change it correctly. Like the previous answer mentions, if it is really sensitive, cookie is not the place to store it but encryption gives you a little bit more protection.

    0 讨论(0)
提交回复
热议问题