簡體   English   中英

MVC4表單身份驗證自動登錄

[英]MVC4 Forms Authentication Auto Login

因此,我要完成的工作是為我的應用程序用戶提供一個基本的“記住我”樣式的操作。

到目前為止,我已經完成了所有內容的編寫,並且大多數時候都可以按預期進行。 不過,有時候,檢查持久性Forms Authentication票證的方法不會自動登錄,而且我不知道為什么它只是偶爾發生。

要測試我的代碼,我要做的是啟動調試器,在chrome的dev工具中手動殺死我的會話cookie,然后重新加載頁面。 逐步執行代碼,它按預期進入自動登錄方法,然后繼續重置我的會話數據。 但是,如果我等待的時間過長(例如大約4個小時),然后嘗試相同的操作,它不會自動重置會話。 (假設我已經讓調試器運行了一段時間。)

編輯 :為清楚起見,當發生此錯誤時,我可以打開開發工具並查看身份驗證票證仍然可用。 只是用於重置我的會話的代碼未在運行,原因是某個地方出錯了。 由於這種情況發生的頻率不高,因此很難追蹤。

所以,到代碼上。

我在控制器的構造函數中調用靜態void自動登錄方法,並將httpcontext傳遞到自動登錄方法中。

控制者

public class SiteController : Controller
{
    public SiteController()
    {
       this.UserAutoLogin(System.Web.HttpContext.Current);
    }

    // GET: /Site/
    public ActionResult Index()
    {
        ViewBag.CatNav = this.RenderNavCategories();
        return View();
    }
}

自動登錄代碼

public static void UserAutoLogin(this Controller Controller, System.Web.HttpContext context)
{
    HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);

    if (cookie != null)
    {
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

        if (ticket != null)
        {
            if (ticket.Name.Length > 0)
            {
                try
                {
                    if (context.Session["UserName"] == null)
                    {
                        //get user from db
                        PersonRepository PersonRepo = new PersonRepository();
                        PersonModel Member = PersonRepo.GetUserUserName(ticket.Name);

                        if (Member.FirstName != null) //if this is null...then the cookie is wrong, so don't do shit
                        {
                            //Set the session parameters
                            context.Session["FirstName"] = Member.FirstName;
                            context.Session["LastName"] = Member.LastName;
                            context.Session["UserId"] = Member.Id;
                            context.Session["UserName"] = Member.Username;
                            context.Session["Email"] = Member.Email;
                            context.Session["IsUser"] = 1;
                            context.Session["Zip"] = Member.Zip;

                            FormsAuthentication.SignOut();
                            FormsAuthentication.SetAuthCookie(Member.Username, true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    // don't do anything for now - do something smart later :)                        
                    Console.WriteLine(ex.ToString());
                }
            }
        }
    }
}

因為當IIS回收應用程序時,會生成一個新的機器密鑰。 FormsAuthentication票證是使用該密鑰簽名的,因此當密鑰更改時,舊票證將無法識別。 您需要使用固定的機器鑰匙。

編輯 :刪除了到密鑰生成器站點的鏈接(現已終止)

暫無
暫無

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

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