簡體   English   中英

OWIN身份驗證Cookie信息,即使未過期也強制登錄

[英]OWIN Authentication Cookie information and forcing login even when not expired

我想為MVC 5(OWIN)網站的身份驗證Cookie提供兩項功能:-

  • 顯示每個用戶的Cookie到期時間
  • 即使cookie沒有過期也強制登錄

用戶登錄后,該cookie及其包含的聲明就在其瀏覽器上。

我已經設法獲取了cookie信息,盡管它在每次訪問服務器時都會這樣做。

就強制登錄而言,我要么必須更新cookie(如果用戶未與站點進行交互,就不可能更新),要么在每次登錄時按名稱查找用戶。

我的答案如下-如果有人有更好的答案,請告訴我

在OWIN啟動類中,我添加了自定義身份驗證方法。 管理員可以在身份數據庫中設置一個字段,以強制下次登錄。 缺點是每次用戶訪問網頁時數據庫上的命中。

如果用戶這次必須登錄,則清除“強制登錄”標志,用戶注銷並重定向到主頁,然后轉到主頁(並在登錄后重定向回主頁)。

此代碼還檢索cookie信息,以顯示在管理員可以查看的用戶列表中。

private static Task MyCustomValidateIdentity(CookieValidateIdentityContext context)
        {
            var db = ApplicationDbContext.Create();
            var userName = context.Identity.GetUserName();
            var user = (from u in db.Users where u.UserName == userName select u).FirstOrDefault();

            if (user != null)
            {
                if (user.ForceLoginNextTime)
                {
                    user.ForceLoginNextTime = false;
                    db.SaveChanges();

                    context.OwinContext.Authentication.SignOut(context.Options.AuthenticationType);
                    context.Response.Redirect("/Home");
                }
            }

            var i = (from u in __userInfo where u.userName == userName select u).FirstOrDefault();

            if (i == null)
            {
                i = new UserInfo();
                __userInfo.Add(i);
            }

            i.userName = userName;
            i.CookieIssuedUtc = context.Properties.IssuedUtc;
            i.CookieExpiresUtc = context.Properties.ExpiresUtc;
            i.CookieIsPersistent = context.Properties.IsPersistent;

            return Task.FromResult(0);
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM