I am writing a custom login - On Logout i clear cookies
public ActionResult Logout()
{
Session.Remove("Username");
Session.Clear();
if (Request.Cookies["Username"] != null)
{
HttpCookie usercookie = new HttpCookie("Username");
usercookie.Expires =DateTime.Now.AddDays(-1);
Response.Cookies.Add(usercookie);
Response.Cookies.Set(usercookie);
}
if (Request.Cookies["Password"] != null)
{
HttpCookie usercookie = new HttpCookie("Password");
usercookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(usercookie);
Response.Cookies.Set(usercookie);
}
ViewBag.Error = "Logged out !!clear cookie";
return RedirectToAction("Account","Home");
}
Logout works fine ,but on browser back button i get user name password back even though i cleared cookies on logout.
Related
I am using windows authentication in ASP.NET MVC.
I want to Logout? So I researched and found the following
The code is based on decompiling the Microsoft.TeamFoundation.WebAccess which has the "Sign in as a different User" function.
public ActionResult LogOut()
{
HttpCookie cookie = Request.Cookies["TSWA-Last-User"];
if(User.Identity.IsAuthenticated == false || cookie == null || StringComparer.OrdinalIgnoreCase.Equals(User.Identity.Name, cookie.Value))
{
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 = 0x191;
Response.Clear();
//should probably do a redirect here to the unauthorized/failed login page
//if you know how to do this, please tap it on the comments below
Response.Write("Unauthorized. Reload the page to try again...");
Response.End();
return RedirectToAction("Index");
}
cookie = new HttpCookie("TSWA-Last-User", string.Empty)
{
Expires = DateTime.Now.AddYears(-5)
};
Response.Cookies.Set(cookie);
return RedirectToAction("Index");
}
Is the above code reliable?
ANd how to redirect to another page like logout succesful
after response.clear??
I set cookie when login success like this :
public JsonResult LoginWithPassword(String password)
{
Response.Cookies.Remove("Auth");
string CookieName = "Auth";
long UserId = 4;
HttpCookie myCookie = HttpContext.Response.Cookies[CookieName] ?? new HttpCookie(CookieName);
myCookie.Values["UserId"] = UserId.ToString();
myCookie.Values["LastVisit"] = DateTime.Now.ToString();
myCookie.Expires = DateTime.Now.AddDays(1);
HttpContext.Response.Cookies.Add(myCookie);
return Json(new { IsSuccess = true, ReturnUrl = returnUrl });
}
else
{
return Json(new { IsSuccess = false, Message = "Login fail, Wrong Password" });
}
}
and i read it in next page/action :
public ActionResult Index()
{
if (HttpContext.Request.Cookies["Auth"] == null)
return RedirectToAction("Login", "Access");
return View();
}
Really strange the cookie of "Auth" always empty. When i check the expiration date in debugging breakpoint, i get expiration date : 01/01/0001.
why this happend and how to solve this?
This action in two differents controller
I have tried to implement your code to create cookie. Same code is working fine in MVC5 at my end in firefox browser.
I have used code as below to create cookie -
Response.Cookies.Remove("Auth");
string CookieName = "Auth";
HttpCookie cookie = HttpContext.Response.Cookies[CookieName] ?? new HttpCookie(CookieName);
//HttpCookie cookie = new HttpCookie("Cookie");
cookie.Value = "Hello Cookie! CreatedOn: " + DateTime.Now.ToShortTimeString();
cookie.Expires = DateTime.Now.AddDays(5);
this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
In addition the check on "Auth" cookie is successful on Index page as -
public ActionResult Index()
{
if (HttpContext.Request.Cookies["Cookie"] == null)
return RedirectToAction("Login", "Account");
return View();
}
Alternatively I suggest to
1) Set Expiry after cookie is created in login page OR
2) add decimal in expiry days eg. 1.0 or 5.0. See article at link -
http://forums.asp.net/t/1982279.aspx?MVC5+Application+Cookie+expires+when+session+ends
Let me know if this helps you.
I have an overlay div inside a condition. If Cookies["User"] is null then I show an overlay div having two radio buttons and a submit button.
When user selects radio option and clicks submit button, when by ajax call,
I am calling an action which sets cookies.
I have put the overlay div inside _Layout page, so for every call it checks for session.
My issue is: First time after setting cookies, it's not persisted for second time.
Below is my method which sets cookies:
public ActionResult SaveUserTypeCookies(string usertype, string returnUrl)
{
if (Request.Cookies["User"] != null)
{
HttpCookie cookie = Request.Cookies["User"];
cookie.Values["UserType"] = usertype;
cookie.Expires = DateTime.MaxValue;
Response.SetCookie(cookie);
}
else
{
HttpCookie cookie = new HttpCookie("User");
cookie.Values["UserType"] = usertype;
cookie.Expires = DateTime.MaxValue;
Response.Cookies.Add(cookie);
}
return Redirect(returnUrl);
}
Below is my condition for overlay div:
#if ((Request.Cookies["User"]== null))
{
<div id="overlay_div" class="overlay"></div>
}
Use this syntax to get cookie:
HttpCookie cookie = HttpContext.Request.Cookies.Get("User");
And check if cookie exists use this in C#:
HttpContext.Request.Cookies["User"] != null
And to create and save cookie:
HttpCookie cookie = new HttpCookie("User");
cookie.Values["UserType"] = usertype;
cookie.Expires = DateTime.MaxValue;
HttpContext.Response.SetCookie(cookie);
<authorization><deny users="?"/></authorization>
I kept the above code snippet in web.config file after authentication and the problem started I am entering the correct credentials but still I am not redirecting to next page after successful login
and my new url is being appended with some query string values
this is my login url:
http://localhost:49841/LMIT/Login
After submitting the login form with correct credentials, instead of redirecting to next page, it still stays on the same page with http://localhost:49841/LMIT/Login?ReturnUrl=%2fLMIT%2fIndex in the url
Ok, try the following code:
[AllowAnonymous]
public ActionResult Login(Users user)
{
Users DbData = (from s in db.Users where s.UserName == user.UserName select s).First();
if (DbData != null)
{
if (user.UserName == DbData.UserName && user.Password == DbData.Password)
{
FormsAuthentication.SetAuthCookie(user.Id.ToString(), true);
return Json(new { ok = true, newurl = Url.Action("/Index") });
}
}
return View();
}
Thank everyone read my topic. But i need your help !
I've got a problem with Asp.NET MVC Action.
In HomePage. I have a link redirect to an action call checkTicket(), but require login.
So, in checkTicket() method. I'm using following code to check permision
if (Request.IsAuthenticated)
{
return View();
}
else
{
return RedirectToAction("Login", "Account");
}
But in action Login of Account controller. How can i return back to checkTicket's View() ?
This is something i want.
HomePage (click) -> checkTicket (require) -> Login (return) -> checkTicket()
Create a cookie that is set, letting you know that the user wants to checkticket but is not logged in:
if (Request.IsAuthenticated)
{
return View();
}
else
{
//The cookie's name is UserSettings
HttpCookie myCookie = new HttpCookie("UserSettings");
//The subvalue of checkticket is = true
myCookie["checkticket"] = "true";
//The cookie expires 1 day from now
myCookie.Expires = DateTime.Now.AddDays(1d);
//Add the cookie to the response
Response.Cookies.Add(myCookie);
return RedirectToAction("Login", "Account");
}
Then in your Login Action, check if the cookie exists like so:
if (Request.Cookies["UserSettings"] != null)
{
string userSettings;
if (Request.Cookies["UserSettings"]["checkticket"] != null)
{
userSettings = Request.Cookies["UserSettings"]["checkticket"];
}
if(userSettings) {
//redirect to checkticket
} else {
// redirect to your normal view
}
}
*Code courtesy of MSDN: write cookie, read cookie