實現「同一帳號同一時間僅能在一處登入」:新登入時踢除舊 Session。核心思路 — 在 Session (應用程式域共享) 中維護 Dictionary<Guid, UserInfo> 對應「登入 Token → 使用者」,Cookie 存放 Token,新登入時檢查並移除舊 Token。
// 全域靜態或存於 Application/Redis
// Key: LoginToken (Guid), Value: UserInfo
static readonly Dictionary<Guid, UserInfo> LoginUserList = new Dictionary<Guid, UserInfo>();
public bool Login(string username, string password, HttpResponse response, HttpSessionState session)
{
// 1. 驗證帳密 (略)
var user = ValidateUser(username, password);
if (user == null) return false;
// 2. 產生新 Token
Guid newToken = Guid.NewGuid();
// 3. 檢查該使用者是否已有舊 Token (單點登入核心)
var existingTokens = LoginUserList
.Where(kvp => kvp.Value.UserId == user.UserId)
.Select(kvp => kvp.Key)
.ToList();
foreach (var oldToken in existingTokens)
{
LoginUserList.Remove(oldToken); // 踢除舊 Session
// 可選:通知舊 Session 失效 (SignalR / 輪詢 / 下次請求檢查)
}
// 4. 註冊新 Token
LoginUserList[newToken] = user;
session["LOGIN_USER_LIST"] = LoginUserList; // 同步至當前 Session (若用 InProc)
// 或直接操作共享存儲 (Redis)
// 5. 寫入 Cookie (HttpOnly, Secure, SameSite)
var cookie = new HttpCookie("LOG_USER_KEY", newToken.ToString())
{
HttpOnly = true,
Secure = true, // 僅 HTTPS
SameSite = SameSiteMode.Lax,
Expires = DateTime.Now.AddDays(7)
};
response.Cookies.Add(cookie);
return true;
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Guid token;
if (!Guid.TryParse(Request.Cookies["LOG_USER_KEY"]?.Value, out token) ||
!LoginUserList.ContainsKey(token))
{
// Token 無效或被踢除
FormsAuthentication.SignOut();
Response.Redirect("~/Login.aspx?kicked=1");
}
}
// Key: "login:user:{userId}" → Value: currentToken (Guid)
// Key: "login:token:{token}" → Value: UserInfo (JSON)
public bool LoginDistributed(string username, string password)
{
var user = ValidateUser(username, password);
if (user == null) return false;
string tokenKey = $"login:token:{Guid.NewGuid()}";
string userTokenKey = $"login:user:{user.UserId}";
// Lua 腳本原子操作:設定新 token、刪除舊 token
string lua = @"
local old = redis.call('GET', KEYS[1])
if old then redis.call('DEL', 'login:token:' .. old) end
redis.call('SET', KEYS[1], ARGV[1])
redis.call('SET', KEYS[2], ARGV[2])
return 1";
redis.Eval(lua, new[] { userTokenKey, tokenKey }, user.UserId.ToString(), Serialize(user));
// 寫 Cookie...
return true;
}
HttpOnly; Secure; SameSite=Strict。