萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

.NET 限制使用者單點登入:Session + Cookie 實作踢除舊登入

實現「同一帳號同一時間僅能在一處登入」:新登入時踢除舊 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;
}

每次請求驗證 (BasePage 或 ActionFilter)

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");
    }
}

分散式環境 (多台 Web Server) 改用 Redis

// 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;
}

安全性補強

  • Token 使用 加密簽名 JWT 或 隨機 Guid + 伺服器端驗證,避免客戶端偽造。
  • Cookie 設定 HttpOnly; Secure; SameSite=Strict。
  • 敏感操作 (修改密碼、綁定手機) 需**二次驗證** (簡訊/Email/OTP),即使 Token 被竊也無法完成高風險操作。
copyright © 萬盛學電腦網 all rights reserved