DIV CSS 佈局教程網

用 Cookie 記住使用者名稱與密碼:兩種實作與安全提醒
編輯:關於JavaScript     

「記住我」是登入表單的常見功能,做法是把使用者名稱與密碼寫進 Cookie,下次開啟頁面時自動帶入。這裡提供兩種寫法,但請先看完最後的安全段落再決定要不要用。

方式一:cookie.js + common.js 分工

檔案結構包含 login.html、welcome.html、cookie.js(Cookie 讀寫工具)與 common.js(表單邏輯)。

login.html

<form action="">
  <p><span>UserName:</span> <input id="userName" type="text" value="" /></p>
  <p><span>Password:</span> <input id="password" type="password" value="" /></p>
  <p><span style="font-size:12px; color:blue;">記住密碼</span>
     <input id="saveCookie" type="checkbox" value="" /></p>
  <p><input id="submit" type="button" value="GO" /></p>
</form>
<script type="text/javascript" src="cookie.js"></script>
<script type="text/javascript" src="common.js"></script>

cookie.js

// hours 為空字串時,Cookie 存活到瀏覽器工作階段結束;
// hours 為 0 時會建立一個立即失效的同名 Cookie,用以覆蓋舊值
function setCookie(name, value, hours, path) {
  var name = escape(name);
  var value = escape(value);
  var expires = new Date();
  expires.setTime(expires.getTime() + hours * 3600000);
  path = path == "" ? "" : ";path=" + path;
  _expires = (typeof hours) == "string" ? "" : ";expires=" + expires.toUTCString();
  document.cookie = name + "=" + value + _expires + path;
}

function getCookieValue(name) {
  var name = escape(name);
  var allcookies = document.cookie;
  name += "=";
  var pos = allcookies.indexOf(name);
  if (pos != -1) {
    var start = pos + name.length;
    var end = allcookies.indexOf(";", start);
    if (end == -1) end = allcookies.length;
    return allcookies.substring(start, end);
  }
  return "";
}

function deleteCookie(name, path) {
  var name = escape(name);
  var expires = new Date(0);
  path = path == "" ? "" : ";path=" + path;
  document.cookie = name + "=" + ";expires=" + expires.toUTCString() + path;
}

common.js

function $(objStr) { return document.getElementById(objStr); }

window.onload = function () {
  // 還原上次的登入資訊
  $("userName").value = getCookieValue("userName");
  $("password").value = getCookieValue("password");

  $("submit").onclick = function () {
    var userNameValue = $("userName").value;
    var passwordValue = $("password").value;

    // 這裡只是模擬的伺服器驗證
    var isAdmin = userNameValue == "admin" && passwordValue == "123456";
    var isUserA = userNameValue == "userA" && passwordValue == "userA";
    if (isAdmin || isUserA) {
      if ($("saveCookie").checked) {
        setCookie("userName", $("userName").value, 24, "/");
        setCookie("password", $("password").value, 24, "/");
      }
      alert("登入成功,歡迎你," + userNameValue + "!");
      self.location.replace("welcome.html");
    } else {
      alert("使用者名稱或密碼錯誤,請重新輸入!");
    }
  };
}

方式二:單檔版本,以 GUID 區分使用者

這版本用一個 GUID 當作「最後登入者」的 Cookie 名,再以使用者名稱作為密碼的 Cookie 名,並在 username 失焦時呼叫 GetPwdAndChk() 帶出對應密碼。關鍵函式如下:

function SetPwdAndChk() {
  var usr = document.getElementById('txtUserName').value;
  SetLastUser(usr);                       // 記住最後一位使用者

  if (document.getElementById('chkRememberPwd').checked == true) {
    var pwd = document.getElementById('txtPassword').value;
    var expdate = new Date();
    expdate.setTime(expdate.getTime() + 14 * (24 * 60 * 60 * 1000)); // 兩週
    SetCookie(usr, pwd, expdate);
  } else {
    ResetCookie();                        // 沒勾選就立刻失效
  }
}

function SetLastUser(usr) {
  var id = "49BAC005-7D5B-4231-8CEA-16939BEACD67";
  var expdate = new Date();
  expdate.setTime(expdate.getTime() + 14 * (24 * 60 * 60 * 1000));
  SetCookie(id, usr, expdate);
}

function GetPwdAndChk() {
  var usr = document.getElementById('txtUserName').value;
  var pwd = GetCookie(usr);
  if (pwd != null) {
    document.getElementById('chkRememberPwd').checked = true;
    document.getElementById('txtPassword').value = pwd;
  } else {
    document.getElementById('chkRememberPwd').checked = false;
    document.getElementById('txtPassword').value = "";
  }
}

function GetCookie(name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg) { return getCookieVal(j); }
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break;
  }
  return null;
}

function getCookieVal(offset) {
  var endstr = document.cookie.indexOf(";", offset);
  if (endstr == -1) endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}

function SetCookie(name, value, expires) {
  var argv = SetCookie.arguments;
  var argc = SetCookie.arguments.length;
  var expires = (argc > 2) ? argv[2] : null;
  var path    = (argc > 3) ? argv[3] : null;
  var domain  = (argc > 4) ? argv[4] : null;
  var secure  = (argc > 5) ? argv[5] : false;
  document.cookie = name + "=" + escape(value)
    + ((expires == null) ? "" : ("; expires=" + expires.toGMTString()))
    + ((path == null) ? "" : ("; path=" + path))
    + ((domain == null) ? "" : ("; domain=" + domain))
    + ((secure == true) ? "; secure" : "");
}

function ResetCookie() {
  var usr = document.getElementById('txtUserName').value;
  SetCookie(usr, null, new Date());
}

請務必讀完這段:不要這樣存密碼

上面兩種寫法都把明文密碼寫進 Cookie,這在真實環境中是嚴重的安全漏洞。Cookie 會隨每次請求自動送往伺服器,任何能攔截流量的人(例如未加密的 HTTP 或惡意中繼)都能直接讀到;使用者也能從開發者工具輕易看到。此外,範例中的 escape() / unescape() 已被淘汰,請改用 encodeURIComponent()。

正確的做法是:

一、只記使用者名稱,不記密碼。絕大多數網站就是這樣做,體驗已經足夠。

二、需要「保持登入」時,用伺服器核發的 token。登入成功後由後端產生一組隨機 token 存進資料庫,前端只保存這個 token(建議放在 HttpOnly + Secure + SameSite 的 Cookie 中,讓 JavaScript 讀不到),後續請求以它換取工作階段。

三、密碼永遠不要存在前端。無論是 Cookie、localStorage 還是 sessionStorage,都不具備保存憑證的能力。真正的驗證必須在伺服器端完成,且密碼應以 bcrypt、scrypt 或 Argon2 這類慢速雜湊加鹽存放。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved