Should I prevent JavaScript injections in password field?

1k Views Asked by At

I've found lots of information about JavaScript injections, but didn't find any specific regarding password field.

For my test GMail account I was able to set the next password <Script>alert(document.cookie);</script> and it works correctly. enter image description here enter image description here

Should I just encode the < and > to their HTML equivalent?

How to handle such passwords?

Edit #1: I store passwords in DB as hashes (and no issues for JavaScript injections here). And I want to add a toggle for Password Visibility. In this case I should encode the < and > to their HTML equivalent and that's it?

1

There are 1 best solutions below

0
Alex Kulinkovich On BEST ANSWER

I used the next advice:

  1. you should store passwords in DB as hashes (no issues for JavaScript injections here).
  2. for a Password toggle Visibility:

    2.1 if it is implemented with a plain <input>, you don't have to do anything (no JavaScript injections here).

    2.2 if it is implemented with a <span>, <div>, etc, then you have to HTML-encode it (and note that you also have to worry about & characters).

<!DOCTYPE html>
<html>
<body>

Password: <input type="password" value="<Script>alert(document.cookie);</script>" id="myInput"><br><br>
<input type="checkbox" onclick="showPasswd()">Show Password

<script>
function showPasswd() {
  var x = document.getElementById("myInput");
  if (x.type === "password") {
x.type = "text";
  } else {
x.type = "password";
  }
}
</script>

</body>
</html>