Logout a user using Ajax

I’m using forms authentication.

When I call the below WebMethod via jQuery/Ajax it does NOT logoff the user. Why not? I know it calls the method, but does not work?



        [WebMethod]
        public static void LogOff()
        {
            _Default page = new _Default();
            
            FormsAuthentication.SignOut();
            FormsAuthentication.RedirectToLoginPage();
            //page.Response.Redirect("../Default.aspx");
        }


You cannot redirect in an ajax request as you are basically redirecting the ajax call. So all you get is a different response. Why would you want to log a user out using ajax anyway? Redirecting in an ajax call is anyway defeating the point of ajax, you might as well just use a normal postback

Right, so forget the redirect. What if I want to log them out then return a response that says, “You are now logged out”… The FormsAuthentication.SignOut(); is not working?
I close the browser, return to the page and it still has me logged in?

hmmm that is interesting. It is very hard for me to think of the problem as I never us MS Ajax, jQuery handles all my ajax needs.

Providing the code is within the scope of your site and not another domain/sub-domain it should work.

What is the response of the ajax call? And is it working or throwing any errors? Check the the Console section of firebug(the firefox add-in)

Can you post your code in function Login ? I need to know what you did on login and logout, so I can help you solve this problem.

Here’s my guess:

Forms Auth keeps track of whether you are logged in using cookies (usually that’s the way people configure it). So the browser isn’t clearing the cookie without a full page redirect.

So you will need to take the user out of your current page and over to another (like a login page) in order to get the cookie cleared.

@NightStalker-DNS - I’m using jQuery to call the WebMethod. I can set a break point and so I know it’s getting there. It throws no error.

@dzflip - here is some code for the login, I already posted the code for logout.

So the browser isn’t clearing the cookie without a full page redirect.

Ok, I guess that could be it? So if I send them to the login page on the return trip of the Ajax call it should work?

Also, what if they close the browser and never hit the logout button?


protected void Page_Init(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.Cookies["teeTimeCookie"] != null)
                {
                    HttpCookie cookie = Request.Cookies.Get("teeTimeCookie");
                    Login1.UserName = cookie.Values["username"];
                    Login1.RememberMeSet = (!String.IsNullOrEmpty(Login1.UserName));
                }

                TextBox txtUser = Login1.FindControl("userName") as TextBox;

                if (txtUser != null)
                {
                    this.SetFocus(txtUser);
                }
            }

            // Note this
            Response.Cache.SetNoStore();
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ViewState["LoginErrors"] = 0;
            }
        }

        protected void Login1_LoginError(object sender, EventArgs e)
        {
            CustomValidator val = new CustomValidator();
            val.IsValid = false;
            val.ErrorMessage = Login1.FailureText;
            val.ValidationGroup = "Login1";
            this.Page.Validators.Add(val);
        } 

        protected void Login1_LoggedIN(object sender, EventArgs e)
        {
            HttpCookie teeTimeCookie = new HttpCookie("teeTimeCookie");
            Boolean remember = Login1.RememberMeSet;

            if (remember)
            {
                var persistDays = 30;
                teeTimeCookie.Values.Add("username", Login1.UserName);
                teeTimeCookie.Expires = DateTime.Now.AddDays(persistDays); //you can add years and months too here
            }
            else
            {
                teeTimeCookie.Values.Add("username", string.Empty); // overwrite empty string is safest
                teeTimeCookie.Expires = DateTime.Now.AddMinutes(5); //you can add years and months too here
            }

            Response.Cookies.Add(teeTimeCookie);
        }


You can use code below:
ajax logout

 function UserSignOut() {
        $.ajax({
            url: '/SignOut.aspx',
            cache: false,
            success: function(msg) {
                window.location.href = window.location;
            }
        }); 

function Logout in SignOut.aspx:

protected void Page_Load(object sender, EventArgs e)
        {
            // Log User Off from Cookie Authentication System
            FormsAuthentication.SignOut();
        }

AFAIK when doing a AJAX request the cookies send with the response aren’t applied. So you need to remove the cookie on the client side using javascript (you can find plenty of samples). The only information you’ll need is the cookie name (configured on the server FormsAuthentication.FormsCookieName).

The only problem might be, that Forms authentication passes the authentication cookie as HttpOnly (which means you can’t access it using javascript). You’ll have to turn that feature off somehow.

As nightstalker said, it seems you are using Ajax for the sake of it, and not for what it is meant to be used for.

Simply send the user to a page that does the logout, which in turn takes them back the home page.