2016年5月15日 星期日

[ASP.NET] Windows Authentication - Logout

 ASP.NET   Windows Authentication   logout


Background


I got a requirement that the user can logout the windows-authentication-based web application and logon as another user.

There is a browser’s solution which could disable the intranet auto-logon option in IE. Thus every time an user opens or closes the web application thru any browser, he/she has to key in the AD user name and password to be authorized.




However, this is a bad solution cus it disables the auto-logon on all the intranet websites. And of course, setting every client’s browser settings is never a good idea.

Here is a programmatic solution on stackflow which was based on decompiling the Microsoft.TeamFoundation.WebAccess which has the "Sign in as a different User" function.

PS. However, the codes cannot runs properly on Chrome! IE and firefox are fine.



Implement


The function will be put on the “logout” link button.


Logout

Here I am using MVC application to make the sample.


/// <summary>
/// Logout
/// </summary>
/// <returns></returns>
public ActionResult Logout()
{
           HttpCookie cookie = Request.Cookies["TSWA-Last-User"];


            #region 重新輸入認證

            if (
                User.Identity.IsAuthenticated == false  //當認證失敗
                || cookie == null  //TSWA-Last-User Cookie is null
                //|| StringComparer.OrdinalIgnoreCase.Equals(User.Identity.Name, cookie.Value) //重新輸入的使用者和Cookie的相同時
                )
            {

                string name = string.Empty;

                if (Request.IsAuthenticated)
                {
                    name = User.Identity.Name;
                    cookie = new HttpCookie("TSWA-Last-User", name);
                    Response.Cookies.Set(cookie);
                }


                Response.AppendHeader("Connection", "close");
                Response.StatusCode = 401; // Unauthorized;
                Response.Clear();

                //Show not login message
                Response.Write("<h2>認證失敗! 請按F5或重新整理視窗重新登入。</h2>");
                //Or redirect to ?
                //Response.Write("<script>window.location='/Home/login'</script>");

                Response.End();


                Thread.Sleep(5000); //Needs a delay to make sure the popup logon window appear before redirect

                return RedirectToAction("Index");
            }

            #endregion

            #region Clear cookie : 確保下一次登出可進入到"重新輸入認證"

            LogUtility.Logger.Debug("Reset cookie!");
            cookie = new HttpCookie("TSWA-Last-User", string.Empty)
            {
                Expires = DateTime.Now.AddYears(-5)
            };

            Response.Cookies.Set(cookie);

            #endregion


            return RedirectToAction("Index");
}




Result

After click the “Logout”, the logon popup window will show up.






Reference












沒有留言:

張貼留言