核心邏輯流程
- 頁面載入 → 讀取 Cookie → 若「記住我」勾選 → 自動填充用戶名/密碼
- 用戶登錄 → 驗證成功 → 若勾選「記住我」 → 寫入 Cookie (用戶名、密碼、標記)
- 用戶取消勾選 → 清除相關 Cookie
完整實現代碼
HTML 結構
<div class="login-form">
<input id="username" type="text" class="txt1"
value="請輸入用戶名"
data-placeholder="請輸入用戶名" />
<input id="password" type="text" class="txt2"
value="請輸入密碼"
data-placeholder="請輸入密碼" />
<label><input type="checkbox" id="ck_rmbUser" /> 記住我</label>
<button id="loginButton">登錄</button>
<span id="tip" class="error-msg"></span>
</div>
jQuery 邏輯 (依賴 jquery.cookie 插件)
$(function() {
// 1. 頁面初始化:讀取 Cookie 自動填充
if ($.cookie('rmbUser') === 'true') {
$('#ck_rmbUser').prop('checked', true);
$('#username').val($.cookie('username'));
// 密碼框類型切換:text → password
$('#password').replaceWith(
'<input id="password" type="password" class="txt2" />'
);
$('#password').val($.cookie('password'));
}
// 2. 密碼框聚焦時切換為 password 類型 (安全)
$('#username, #password').on('focus', function() {
var $this = $(this);
if ($this.val() === $this.data('placeholder')) {
$this.val('');
if ($this.is('#password')) $this.attr('type', 'password');
}
}).on('blur', function() {
var $this = $(this);
if ($this.val() === '') {
$this.val($this.data('placeholder'));
if ($this.is('#password')) $this.attr('type', 'text');
}
});
// 3. 登錄提交
$('#loginButton').click(function() {
if (validateForm()) {
doLogin();
}
});
// 4. 記住密碼邏輯
function saveRememberMe() {
if ($('#ck_rmbUser').prop('checked')) {
$.cookie('rmbUser', 'true', {expires: 7, path: '/'});
$.cookie('username', $('#username').val(), {expires: 7, path: '/'});
$.cookie('password', $('#password').val(), {expires: 7, path: '/'});
} else {
$.cookie('rmbUser', 'false', {expires: -1, path: '/'});
$.cookie('username', '', {expires: -1, path: '/'});
$.cookie('password', '', {expires: -1, path: '/'});
}
}
function validateForm() {
var u = $('#username').val();
var p = $('#password').val();
if (!u || u === '請輸入用戶名') {
showTip('請輸入用戶名!'); $('#username').focus(); return false;
}
if (!p || p === '請輸入密碼') {
showTip('請輸入密碼!'); $('#password').focus(); return false;
}
showTip(''); return true;
}
function doLogin() {
showOverlay();
$.ajax({
type: 'POST',
url: 'login!loginValidate.action',
data: {userName: $('#username').val(), password: $('#password').val()},
dataType: 'json',
success: function(data) {
if (data.success) {
saveRememberMe(); // 登錄成功後保存
location.href = '/index.jsp';
} else {
hideOverlay();
showTip('用戶名或密碼錯誤!');
}
},
error: function() {
hideOverlay();
showTip('網絡錯誤,請重試');
}
});
}
function showTip(msg) { $('#tip').text(msg); }
function showOverlay() { $('#overlay').show(); }
function hideOverlay() { $('#overlay').hide(); }
});
安全風險與現代替代方案
⚠️ 明文存儲密碼風險
- Cookie 明文傳輸 (需 HTTPS)、客戶端可讀、XSS 竊取風險極高。
- 違反 GDPR、等保 2.0 等合規要求。
現代最佳實踐:Token + 本地存儲
// 登錄成功後
$.ajax({
// ...
success: function(data) {
if (data.success) {
// 1. 存儲 Token (HttpOnly Cookie 或 localStorage)
// 後端設置 HttpOnly; Secure; SameSite=Strict Cookie
// document.cookie = "token=...; HttpOnly; Secure; SameSite=Strict"; // 服務端設置
// 2. 僅存儲用戶名 (非敏感) 供自動填充
if ($('#ck_rmbUser').prop('checked')) {
localStorage.setItem('rememberedUser', $('#username').val());
} else {
localStorage.removeItem('rememberedUser');
}
location.href = '/index.jsp';
}
}
});
// 頁面載入自動填充用戶名
$(function() {
var remembered = localStorage.getItem('rememberedUser');
if (remembered) {
$('#username').val(remembered);
$('#ck_rmbUser').prop('checked', true);
$('#password').focus(); // 直接聚焦密碼框
}
});
瀏覽器內置密碼管理器 (最推薦)
- 表單添加
autocomplete="username" / autocomplete="current-password"。
- 瀏覽器自動提示保存/填充,加密存儲、跨設備同步、防釣魚。
- 無需前端寫任何 Cookie/JS 邏輯。
jquery.cookie 插件必要 API
// 寫入
$.cookie('name', 'value', {expires: 7, path: '/', domain: 'example.com', secure: true});
// 讀取
$.cookie('name'); // "value" 或 undefined
// 刪除
$.cookie('name', '', {expires: -1, path: '/'});
// 或
$.removeCookie('name', {path: '/'});
總結建議
- 新專案禁用明文密碼 Cookie,改用 HttpOnly Token + 瀏覽器密碼管理器。
- 僅記住用戶名 (localStorage),密碼交給瀏覽器/密碼管理器。
- HTTPS 強制:所有認證傳輸必須加密。
- SameSite Cookie:防禦 CSRF,
SameSite=Strict/Lax。
- 定期輪換 Token:Refresh Token 機制,降低洩露影響。