how to signout from form authentication after session end

2k Views Asked by At

My MVC application uses FormsAuthentication to sign in.

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(FiNext.Models.User user)
    {
        try
        {
            using (HttpClient httpClient = new HttpClient())
            {
                var task = httpClient.PostAsJsonAsync<FiNext.Models.User>(String.Concat(ServiceUri.ApiUrl,"/Test/Validate"), user).Result;

                FormsAuthentication.SetAuthCookie(user.Name, false);
                SessionHelpers.UserId = user.Id;
                return RedirectToAction("Create");

            }
        }

And it has a Session time out of 1 minute(in web.config) and once the session time out is called ,I am clearing sessions in session_end event in Global.asax.

    protected void Session_End(object sender, EventArgs e)
    {
        Session.Clear();
        Session.Abandon();
    }

Now the problem when i sign out using normal log off button on the page,the page gets signed out.

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOff()
    {
        try
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Home", "User");
        }
        catch (Exception ex)
        {                
            throw ex;
        }
    }

and now i hit any url of this application(say "http://abcd.com/User/UserList") it is redirected to login page as we have logged out and redirecting to home page. This is the desired functionality and working fine.

But the problem is when there is session time out and session_end event is fired.And now when i hit any url of this application(say "http://abcd.com/User/UserList"),iam able to get the data(which should not happen).

So how to signout from forms authentication when session_end is fired. I tried this in session_end event in Global.asax:

    protected void Session_End(object sender, EventArgs e)
    {
        FormsAuthentication.SignOut();
        Session.Clear();
        Session.Abandon();
    }

but its gives "Object reference not set to an instance of an object." exception.

1

There are 1 best solutions below

0
On

Maybe I am missing something, but it sounds like an authorization problem, not a session problem.

Is your UserList action secured in some way?

[Authorize]
public ActionResult UserList()
{
    return View();
}

http://msdn.microsoft.com/en-us/library/ff398049(v=vs.100).aspx