Search code examples
c#asp.netwindows-authentication

How to Logout button Windows Authentication in asp.net application


In my Project I am using Windows Authentication Login. Logout Button is Required.

If Click on Logout Button Page should be redirect to Logout.aspx. In Logout.aspx if I press Back Button in Browser that is redirect back.

How To control should not redirect to back In LogOut Page and Ask for Window Authentication Login?


Solution

  • I have a Web-form solution for this , you can use it , I hope be useful for you.

    logout.aspx

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="logout.aspx.cs" Inherits="logout" %>
    
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <meta http-equiv="Cache-Control" content="no-cache">
        <meta http-equiv="Pragma" content="no-cache">
        <meta http-equiv="Expires" content="0">
    </head>
    <body>
        <script type="text/javascript">
            function HandleResult(arg, context) {
                window.location = "/Login.aspx";
            }
        </script>
        <form id="form1" runat="server">
        </form>
        <script>
            CallServer('LoGout', '');
                var Backlen=history.length;   
            history.go(-Backlen);   
            window.location.href = "/Login.aspx";
    
        </script>
    </body>
    </html>
    

    logout.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    
    public partial class logout : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
    {
        public void RaiseCallbackEvent(string eventArgument)
        {
        }
    
        public string GetCallbackResult()
        {
            return "";
        }
    
        protected void Page_Load(object sender, EventArgs e)
        {
            ClearAll();
            ClientScriptManager cm = Page.ClientScript;
            string cbReference = cm.GetCallbackEventReference(this, "arg", "HandleResult", "");
            string cbScript = "function CallServer(arg, context){" + cbReference + ";}";
            cm.RegisterClientScriptBlock(this.GetType(), "CallServer", cbScript, true);
            cm.RegisterStartupScript(this.GetType(), "cle", "windows.history.clear", true);
            Response.Redirect("/login.aspx");
    
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            ClearAll();
        }
    
        void ClearAll()
        {
            Session.RemoveAll();
            System.Web.Security.FormsAuthentication.SignOut();
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
            Response.Cache.SetNoStore();
    
    
        }
    }
    

    I Have this in my projects that working fine.