MVC: cookies are not persisting - asp.net-mvc

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);

Related

How to retain page state when selecting language in Multi Language Implementation using ASP.Net MVC?

I am using the following controller method to store the selected language and return to the Home page when users changes the selected language.
Is there a way I can redirect to the same page which the user is viewing right now with a change in display language instead of redirecting to Home Page.
public ActionResult SetCulture(string culture)
{
string test = this.ControllerContext.RouteData.Values["action"].ToString();
// Validate input
culture = CultureHelper.GetImplementedCulture(culture);
// Save culture in a cookie
HttpCookie cookie = Request.Cookies["_culture"];
if (cookie != null)
cookie.Value = culture; // update cookie value
else
{
cookie = new HttpCookie("_culture");
cookie.Value = culture;
cookie.Expires = DateTime.Now.AddYears(1);
}
Response.Cookies.Add(cookie);
return RedirectToAction("Index");
}

Back button shows password,username.Even though Cookies are expired?

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.

Windows Authentication Logout / SigninwithDifferent User

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??

FormsAuthentication and Ajax Requests

I have a problem knowing whether a user is authenticated or not when ajax requests are sent from jQuery.
HttpContext.User.Identity is not empty when a user does a regular request from their browser and the aspxauth cookie is set. When a user tries doing a ajax request from jQuery, the aspxauth is not set at all.
My Web.Config
<authentication mode="Forms">
<forms loginUrl="~/" />
</authentication>
Setting the FormsAuthentication Cookie
var cookie = new AuthCookie
{
UserId = user.UserId,
Email = user.Email,
Name = user.Name,
RememberMe = createPersistentCookie,
TimeZone = user.TimeZone,
CompanyId = user.CompanyId,
Roles = new List<string> { user.Role ?? "user" }
};
string userData = JsonConvert.SerializeObject(cookie);
var ticket = new FormsAuthenticationTicket(1, cookie.Email, DateTime.Now,
DateTime.Now.Add(FormsAuthentication.Timeout),
createPersistentCookie, userData);
string encTicket = FormsAuthentication.Encrypt(ticket);
var httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { Expires = DateTime.Now.Add(FormsAuthentication.Timeout) };
_httpContext.Response.Cookies.Add(httpCookie);
When I make requests through my broser, the auth cookie appears:
Whenever I make a request through javascript using $.get() or loading javascript scripts / Any other request through javascript, I get:
The odd thing is that on another ASP application I am using WebSecurity and that works perfectly. The auth cookie is always being sent back from client to server. For this ASP MVC 5 application, when I try to use the FormAuthentication, I cannot get the AuthCookie to proceed through all requests.
you are still able to decorate your class/method with [Authorize] and the like. If you're looking to check inside the controller method you have access to the User Property inherited from System.Web.Mvc.Controller or System.Web.Http.ApiController depending on your controller flavor :
//
// Summary:
// Returns the current principal associated with this request.
//
// Returns:
// The current principal associated with this request.
public IPrincipal User { get; set; }
it can be used like so:
if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
{
// user has access - process request
}
Edit:
Here is an example of an [Api]Controller with an ajax[able] method that uses the controller's User property instead of HttpContext's:
public class HelloController : ApiController
{
[HttpGet]
public IHttpActionResult HelloWorld()
{
try
{
if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
{
return Ok("Hello There " + User.Identity.Name + "!");
}
else
{
return Ok("Hello There Anonymous!");
}
}
catch { throw; }
}
}

Set cookie value before view loaded in MVC?

I need to set a cookie value before my view called. otherwise I have to refresh the page to get cookie value in the view. The problem here is the value of cookie will get in controller.
[HttpGet]
[Route("Abstract/{meetingCode}")]
[AllowAnonymous]
public ActionResult Index(string meetingCode)
{
var meetingAbstract = new MeetingAbstract();
meetingAbstract.Meeting = _abstractContext.GetMeetingWithMeetingCode(meetingCode);
if (meetingAbstract.Meeting != null)
{
var cookie = new HttpCookie("_culture");
cookie.Value = meetingAbstract.Meeting.language.language_locale_code;//"en-US";
cookie.Expires = DateTime.Now.AddDays(365);
cookie.Path = "/";
this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
...
Any other way without refresh the page again to set cookie value?
Cookies have some peculiar behaviour, I mean you create them in the Response stream, to be sent to the client, but they are not available in the Request stream until they are sent from the client.
I mean, you cannot access the cookie unless it is being sent from the client.
Anyway, why you need to refresh your page to access the cookie you just created? Is not easier to use the same variable?
[HttpGet]
[Route("Abstract/{meetingCode}")]
[AllowAnonymous]
public ActionResult Index(string meetingCode)
{
var meetingAbstract = new MeetingAbstract();
meetingAbstract.Meeting = _abstractContext.GetMeetingWithMeetingCode(meetingCode);
var cookie;
if (meetingAbstract.Meeting != null)
{
cookie = new HttpCookie("_culture");
cookie.Value = meetingAbstract.Meeting.language.language_locale_code;//"en-US";
cookie.Expires = DateTime.Now.AddDays(365);
cookie.Path = "/";
this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
} else {
cookie = this.ControllerContext.HttpContext.Request.Cookies["_culture"];
}
...

Resources