Before trying my Solution i would like to suggest you
to Just open MVC Application with default Template and check how the default functionality is working for Login
and Logout
.
I'm Sure you can easily identify your mistake and you will get solution.
Also Try the Below given solution which is im using in my project and currently its working fine to me.
In Your App_Start: Create a Class Like Below
public class AuthorizeUser : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.User.Identity.IsAuthenticated) return false;
return base.AuthorizeCore(httpContext);
}
}
In Your Controller :
[AuthorizeUser]
public class UserController : BaseController<Users>
{
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
FormsAuthentication.SignOut();
return RedirectToAction("UserLogin");
}
}
In Your Fillter Config :
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthorizeUser()); // Register Authorize User
}
}
Verify it in Global.ascx:
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
JavaScriptSerializer serializer = new JavaScriptSerializer();
if (authTicket.UserData == "OAuth") return;
}
}
In Your View :
<span>
@using (Html.BeginForm("LogOff", "User", FormMethod.Post, new { id = "logoutform" }))
{
@Html.AntiForgeryToken()
<a href="javascript:document.getElementById('logoutform').submit()">Logoff</a>
}
</span>
Your Login Action Result should have AllowAnonymous
Access in your Conroller:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult UserLogin(LoginViewModel model, string returnUrl) // Model is optional But return URL is required
{
// Do Stuff
}
First / Index Calling of Login
Form :
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View(new LoginViewModel());
}
Return Url is Must in Controller:
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl)) return Redirect(returnUrl);
else return RedirectToAction("UserLogin");
}
Note : Add this in all the Controllers :
[AuthorizeUser]
Good Luck :)