Here is My Code To Log In
var expire = DateTime.Now.AddDays(7);
// Create a new ticket used for authentication
var ticket = new FormsAuthenticationTicket(
1, // Ticket version
username, // Username to be associated with this ticket
DateTime.Now, // Date/time issued
expire, // Date/time to expire
true, // "true" for a persistent user cookie (could be a checkbox on form)
roles, // User-data (the roles from this user record in our database)
FormsAuthentication.FormsCookiePath); // Path cookie is valid for
// Hash the cookie for transport over the wire
var hash = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash) { Expires = expire };
// Add the cookie to the list for outbound response
Response.Cookies.Add(cookie);
Here Is My Code To Check The Roles. It is a custom IHTTP Module
if (HttpContext.Current.User == null) return;
if (!HttpContext.Current.User.Identity.IsAuthenticated) return;
if (!(HttpContext.Current.User.Identity is FormsIdentity)) return;
// Get Forms Identity From Current User
var id = (FormsIdentity)HttpContext.Current.User.Identity;
// Get Forms Ticket From Identity object
var ticket = id.Ticket;
// Retrieve stored user-data (our roles from db)
var userData = ticket.UserData;
var roles = userData.Split(',');
// Create a new Generic Principal Instance and assign to Current User
Thread.CurrentPrincipal = HttpContext.Current.User = new GenericPrincipal(id, roles);
Here is my Code To Log Out
FormsAuthentication.SignOut();
Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
Session.Clear();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetNoStore();
Response.AppendHeader("Pragma", "no-cache");
return View("SignIn");
This is crazy. I have two bald spots now.
1) shouldn't your call to Response.Cookies.Remove(FormsAuthentication.FormsCookieName); be Response.Cookies.Remove(whatever-the-user-name-is);?
2) try sending an expired cookie back to the browser.
FormsAuthentication.SignOut();
// replace with username if this is the wrong cookie name
Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
Session.Clear();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetNoStore();
Response.AppendHeader("Pragma", "no-cache");
// send an expired cookie back to the browser
var ticketExpiration = DateTime.Now.AddDays(-7);
var ticket = new FormsAuthenticationTicket(
1,
// replace with username if this is the wrong cookie name
FormsAuthentication.FormsCookieName,
DateTime.Now,
ticketExpiration,
false,
String.Empty);
var cookie = new System.Web.HttpCookie("user")
{
Expires = ticketExpiration,
Value = FormsAuthentication.Encrypt(ticket),
HttpOnly = true
};
Response.Cookies.Add(cookie);
return View("SignIn");
You can not directly delete a cookie on a client's computer. When you calls the Cookies.Remove method the cookie is deleted on a server side. To delete the cookie on a client's side it's necessary to set the cookie's expiration date to a past date.
HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
cookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Add(cookie);
}
I hope this helps you.
If you want to apply the "no cache on browser back" behavior on all pages then you should put it in global.asax.
protected void Application_BeginRequest()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
}
hope it helps someone !
Related
I would like to know how to properly handle the fact that the cookie expired? Is it possible to execute a custom action ?
What I would like to achieve is that when the cookie is expired is to take few informations out of the current cookie at redirect to a action parametrise by this information. Is it possible ?
There isn't a good way to accomplish this. If the cookie is expired, it is not sent to the server to extract any information. With ASP.Net Core Identity, you don't have much control over that. That leaves you to using Cookie Middleware.
This provides a user to a normal redirect when the cookie is expired:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookieAuthenticationOptions>(options =>
{
options.LoginPath = new PathString("/Home/Index");
});
}
The best way to achieve what you're looking for is to set the cookie expiration much later than the true user session expiration, and then perform your session expiration server side and redirect the user at that point. While it's not ideal, you don't have other options when a cookie is expired.
public void ConfigureServices(IServiceCollection services)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "MyCookieMiddlewareInstance",
// Redirect when cookie expired or not present
LoginPath = new PathString("/Account/Unauthorized/"),
AutomaticAuthenticate = true,
// never expire cookie
ExpireTimeSpan = TimeSpan.MaxValue,
Events = new CookieAuthenticationEvents()
{
// in custom function set the session expiration
// via the DB and reset it everytime this is called
// if the session is still active
// otherwise, you can redirect if it's invalid
OnValidatePrincipal = <custom function here>
}
});
}
It looks like you need your own handler for the OnValidatePrincipal event when setting up cookie authentication middleware:
OnValidatePrincipal event can be used to intercept and override validation of the cookie identity
app.UseCookieAuthentication(options =>
{
options.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = <your event handler>
};
});
The ASP.NET documentation contains an example of such a handler:
public static class LastChangedValidator
{
public static async Task ValidateAsync(CookieValidatePrincipalContext context)
{
// Pull database from registered DI services.
var userRepository = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>();
var userPrincipal = context.Principal;
// Look for the last changed claim.
string lastChanged;
lastChanged = (from c in userPrincipal.Claims
where c.Type == "LastUpdated"
select c.Value).FirstOrDefault();
if (string.IsNullOrEmpty(lastChanged) ||
!userRepository.ValidateLastChanged(userPrincipal, lastChanged))
{
context.RejectPrincipal();
await context.HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance");
}
}
}
It seems there is no event for your case but you can use OnRedirectToLogin to change redirect uri. Here is an example:
OnRedirectToLogin = async (context) =>
{
var binding = context.HttpContext.Features.Get<ITlsTokenBindingFeature>()?.GetProvidedTokenBindingId();
var tlsTokenBinding = binding == null ? null : Convert.ToBase64String(binding);
var cookie = context.Options.CookieManager.GetRequestCookie(context.HttpContext, context.Options.CookieName);
if (cookie != null)
{
var ticket = context.Options.TicketDataFormat.Unprotect(cookie, tlsTokenBinding);
var expiresUtc = ticket.Properties.ExpiresUtc;
var currentUtc = context.Options.SystemClock.UtcNow;
if (expiresUtc != null && expiresUtc.Value < currentUtc)
{
context.RedirectUri += "&p1=yourparameter";
}
}
context.HttpContext.Response.Redirect(context.RedirectUri);
}
In my MVC app I am trying to store a cookie in one page response and access it another:
So my /account/register controller has an action that calls a method to store a cookie
public void StoreCookie(Guid pid)
{
var userCookie = new HttpCookie("Userid","B6EAF085-247B-46EB-BB94-79779CA44A14");
Response.Cookies.Remove("Userid");
Response.Cookies.Add(userCookie);
}
After a user registers I can see that the response(/account/register ) contains the cookie: Userid:"B6EAF085-247B-46EB-BB94-79779CA44A14
I now wish to access this cookie from another MVC page view - info/paymentsuccess
I tried assigning the value to Viewbag as
Viewbag.userid = #Response.Cookies["Userid"].value
This returns null
how do I access this cookie from another page/MVC view and store it in Viewbag.userid?
In your account register controller set the cookie:
HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Userid"];
this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
You can retrieve the cookie like so in your post /account/register controller:
if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Userid"))
{
HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Userid"];
// retrieve cookie data here
}
You can access cookies value in your view using following:
Viewbag.userid = #Request.Cookies["Userid"].value
After registering, do you create a new session? Maybe the cookie is set to the MinValue for Expires, which makes it a session cookie.
Try this:
public void StoreCookie(Guid pid)
{
var userCookie = new HttpCookie("Userid","B6EAF085-247B-46EB-BB94-79779CA44A14");
userCookie.Expires = DateTime.Now.AddDays(1); //...or something that fit your needs
Response.Cookies.Remove("Userid");
Response.Cookies.Add(userCookie);
}
I have read numerous posts where people have had similar issues but have not found a working solution. I have a MVC 4 site, I do not want to remove caching from the entire website as I want to cache the pages. When the user clicks the logoff button it successfully logs off and redirects to the login page, however when the user clicks the back button it shows a previously viewed "restricted page" which you should only be able to see if logged in. I understand that this is because the browser has cached the page client side. I have tried a number of solutions and as mentioned earlier none of them work. Currently my logoff has the following code:
public ActionResult LogOff()
{
FormsAuthentication.SignOut();
Session.Abandon();
Session.Clear();
// clear authentication cookie
HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
cookie1.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie1);
// clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
cookie2.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie2);
// Invalidate the Cache on the Client Side
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetNoStore();
Response.AppendHeader("Pragma", "no-cache");
// send an expired cookie back to the browser
var ticketExpiration = DateTime.Now.AddDays(-7);
var ticket = new FormsAuthenticationTicket(
1,
// replace with username if this is the wrong cookie name
FormsAuthentication.FormsCookieName,
DateTime.Now,
ticketExpiration,
false,
String.Empty);
var cookie = new System.Web.HttpCookie("user")
{
Expires = ticketExpiration,
Value = FormsAuthentication.Encrypt(ticket),
HttpOnly = true
};
Response.Cookies.Add(cookie);
return RedirectToAction("Login", "Account");
}
If you want to apply the "no cache on browser back" behavior on all pages then you should put the following it in global.asax.
protected void Application_BeginRequest()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
}
hope it helps someone !
You could use the hash change event on the browser window, to trigger an ajax request on postback, this would obviously fail as your logged out. From there you could trigger the browser to do anything you like.
Add below lines of code to Global.asax.cs file.
protected void Application_BeginRequest()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
}
Response.ClearHeaders();
Response.AddHeader("Cache-Control", "no-cache, no-store, max-age=0,
must-revalidate");
Response.AddHeader("Pragma", "no-cache");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Buffer = true;
Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
Response.Expires = 0;
Im building a website with the new ASP.NET MVC3 framework and using FormsAuth. for securing the website. I'm storing the role of a user in the UserData property of the FormsAuthenticationTicket, (setting the cookie manually), I then call the encrypt method on the ticket before adding it to the cookie(see below a Standard ticket sniplet).
if (Validate(model.UserName, model.Password))
{
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
model.UserName,
DateTime.Now,
DateTime.Now.AddMinutes(30),
false,
UserType.Administrator.ToString());
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(faCookie);
return RedirectToAction("startpage", "mycontroller");
}
}
Now I've made a custom AuthorizeAttribute thats able to check if the user is 1. authenticated and 2. has the admin role (from the ticket). (below)
The AuthorizeCore method of this derived class will be called when an action takes places in a class that has the attribute annotion.
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
IPrincipal user = httpContext.User;
if (!user.Identity.IsAuthenticated)
{
return false;
}
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = httpContext.Request.Cookies[cookieName];
if (authCookie == null)
return false;
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket.UserData != UserType.Administrator.ToString())
return false;
return true;
So here's where im getting confused.
When I follow the code being executed (with valid credentials, in debug), and check the values of the variables made on each line, the encryptedTicket encrypts just fine before adding it to the reponsecookie.
But when I then check the AuthorizeCore method when the controller (of the index page) is being called, the parameter its getting, the HttpContext, contains the ticket with everything unencrypted, so there is no need to decrypt the ticket anymore when reading the cookie.
Why do I see the ticket succesfully being encrypted in the logon controller where I send it back to the client, but then when I receive the httpcontext in the AuthorizeAdministrator class its all unencrypted again.
Sorry for the long question/story, there's probably a simple and short answer for it.
Hope my story is clear.
Thanks.
Forms auth needs to decrypt the cookie early in the page processing pipeline, to determine if the user is authorized -- that's when it fills in the details for User.Identity, etc.
I am using the following code to set a cookie in my asp.net mvc(C#) application:
public static void SetValue(string key, string value, DateTime expires)
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_request = httpContext.Request;
_response = httpContext.Response;
HttpCookie cookie = new HttpCookie(key, value) { Expires = expires };
_response.Cookies.Set(cookie);
}
I need to delete the cookies when the user clicks logout. The set cookie is not removing/deleting with Clear/Remove. The code is as below:
public static void Clear()
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_request = httpContext.Request;
_response = httpContext.Response;
_request.Cookies.Clear();
_response.Cookies.Clear();
}
public static void Remove(string key)
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_request = httpContext.Request;
_response = httpContext.Response;
if (_request.Cookies[key] != null)
{
_request.Cookies.Remove(key);
}
if (_response.Cookies[key] != null)
{
_response.Cookies.Remove(key);
}
}
I have tried both the above functions, but still the cookie exists when i try to check exist.
public static bool Exists(string key)
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_request = httpContext.Request;
_response = httpContext.Response;
return _request.Cookies[key] != null;
}
What may be problem here? or whats the thing i need to do to remove/delete the cookie?
Clearing the cookies of the response doesn't instruct the browser to clear the cookie, it merely does not send the cookie back to the browser. To instruct the browser to clear the cookie you need to tell it the cookie has expired, e.g.
public static void Clear(string key)
{
var httpContext = new HttpContextWrapper(HttpContext.Current);
_response = httpContext.Response;
HttpCookie cookie = new HttpCookie(key)
{
Expires = DateTime.Now.AddDays(-1) // or any other time in the past
};
_response.Cookies.Set(cookie);
}
The Cookies collection in the Request and Response objects aren't proxies for the cookies in the browser, they're a set of what cookies the browser sends you and you send back. If you remove a cookie from the request it's entirely server side, and if you have no cookies in the response you're just not going to send any thing back to the client, which won't change the set of cookies in the browser at all.
To delete a cookie, make sure that it is in the response cookie collection, but has an expiration time in the past.
Just to add something else I also pass the value back as null e.g.
public static void RemoveCookie(string cookieName)
{
if (HttpContext.Current.Response.Cookies[cookieName] != null)
{
HttpContext.Current.Response.Cookies[cookieName].Value = null;
HttpContext.Current.Response.Cookies[cookieName].Expires = DateTime.Now.AddMonths(-1);
}
}
The best way to implement this is to use a tool like Reflector and see how the System.Web.Security.FormsAuthentication.SignOut method implements removing the authentication cookie.
In Reflector, open up System.Web and navigate to the FormsAuthentication object and find the SignOut method. Right click on it and select "Disassemble" (Choose your language from the menu).
VB.NET
Public Shared Sub SignOut()
FormsAuthentication.Initialize
Dim current As HttpContext = HttpContext.Current
Dim flag As Boolean = current.CookielessHelper.DoesCookieValueExistInOriginal("F"c)
current.CookielessHelper.SetCookieValue("F"c, Nothing)
If (Not CookielessHelperClass.UseCookieless(current, False, FormsAuthentication.CookieMode) OrElse current.Request.Browser.Cookies) Then
Dim str As String = String.Empty
If (current.Request.Browser.Item("supportsEmptyStringInCookieValue") = "false") Then
str = "NoCookie"
End If
Dim cookie As New HttpCookie(FormsAuthentication.FormsCookieName, str)
cookie.HttpOnly = True
cookie.Path = FormsAuthentication._FormsCookiePath
cookie.Expires = New DateTime(&H7CF, 10, 12)
cookie.Secure = FormsAuthentication._RequireSSL
If (Not FormsAuthentication._CookieDomain Is Nothing) Then
cookie.Domain = FormsAuthentication._CookieDomain
End If
current.Response.Cookies.RemoveCookie(FormsAuthentication.FormsCookieName)
current.Response.Cookies.Add(cookie)
End If
If flag Then
current.Response.Redirect(FormsAuthentication.GetLoginPage(Nothing), False)
End If
End Sub
With the above as an example, I was able to create a common method called RemoveCookie() in a shared assembly, code is below:
VB.NET
''' <summary>
''' Method to remove a cookie
''' </summary>
''' <param name="key">Key</param>
''' <remarks></remarks>
Public Shared Sub RemoveCookie(ByVal key As String)
' Encode key for retrieval and remove cookie
With HttpContext.Current
Dim cookie As New HttpCookie(.Server.UrlEncode(key))
If Not IsNothing(cookie) Then
With cookie
.HttpOnly = True
.Expires = New DateTime(&H7CF, 10, 12)
End With
' Remove from server (has no effect on client)
.Response.Cookies.Remove(.Server.UrlEncode(key))
' Add expired cookie to client, effectively removing it
.Response.Cookies.Add(cookie)
End If
End With
End Sub
Having tested this using FireBug and the Cookie add-in for FireBug (in FireFox), I can attest that the cookie immediately gets removed.
Any questions, feel free to message me.
After playing around with this for some time and trying all of the other answers here I discovered that none of the answers here are totally correct.
The part that is correct is that you have to send an expired cookie to effect the deletion. The part that nobody else picked up on (but is demonstrated in the Microsoft code posted by Ed DeGagne) is that the cookie options for the deletion must match exactly the cookie options that were used to set the cookie in the first place.
For example if you originally created the cookie with the HttpOnly option then you must also set this option when deleting the cookie. I expect the exact behavior will vary across browsers and probably over time, so the only safe option that will work long-term is to make sure that all of the cookie options in the deletion response match exactly the cookie options used to create the cookie originally.
Response.Cookies["key"].Expires= DateTime.Now;