IsAuthenticated is always false when including HttpCookie subkeys or not encrypting - c#

Okay, I've been assigned with authenticating used on a login page. I've been working on this for quite a while and decided to clean up it up. The problem that I faced is one of those problems where exceptions aren't thrown, no error is generated, and everything looks okay, but when you try to use a function, it gives back a result that you don't want.
The code I used looks very similar to code from this page:
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthenticationticket.aspx
I've used the code from the demo in my project:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
username,
DateTime.Now,
DateTime.Now.AddMinutes(30),
isPersistent,
userData,
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie myCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
// Create the cookie.
Response.Cookies.Add(myCookie);
So if I logged in, everything works and the below code evaluates to true:
HttpContext.Current.User.Identity.IsAuthenticated;
However, if I wanted to include subkeys to myCookie using either versions:
myCookie.Values.Add("userName", "patrick"); //version 1
myCookie.Values["userName"] = "patrick"; //version 2
Then you add to the cookies collection:
Response.Cookies.Add(myCookie);
Then refresh the page after login:
//This always set to false even after successful log on
HttpContext.Current.User.Identity.IsAuthenticated;
No clue why!
I wanted to do something where I don't have to add the encryption value to the httpcookie immediately:
//IsAuthenticated doesn't work = false
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormCookieName);
cookie.Values.Add("encryptTicket", encTicket);
It's just weird that adding subkeys don't work at all. And that I am forced to encypt a ticket in order to make it work. What I mean, is that IsAuthenticated is false all the time, logged in and authenticated or not. Can anyone try to explain what's going on with this? I have a working solution, but any insight would be helpful.

Okay, think I figured this out. It's because of how my web.config was set up for forms authentication. Using the forms tag.
The FormsAuthenticationTicket looks at that tag for specific information, and if I didn't create a cookie off of it, it wouldn't authenticate me. This was also defaulted to cookieless mode to UseCookies.
But anyways, after I create a cookie off of that, then I become authenticated and then a new session is created for me. After that, I can then provide any extra cookies I want and let the website use them as needed. But as long as that AuthCookie (in my case .ASPXAUTH) is valid, so is my authentication session.
In fact, when I tried to make a cookie session end when the browser closed, by setting the expiration date to MinValue for the cookie and the ticket, I wasn't able to authenticate either! I had to make the ticket last longer than the actual cookie so that the ticket doesn't expire before the cookie does.
The ticket information is really a configuration used to make the cookie, and after cookie creation, the browser is what defines how the cookies are used.

Related

FormsAuthentication Cookie Not Saving

I have two login pages. One for admin users and one for customers.
They both execute the below code (after authorisation) to add a cookie to the Response. The two pages then redirect to the URL provided (I don't do the redirect here as I do some extra checks on admin)
public static string SetAuthCookie<T>
(this HttpResponse responseBase, string name, bool rememberMe, T userData)
{
/// In order to pickup the settings from config, we create a default cookie
/// and use its values to create a new one.
var cookie = FormsAuthentication.GetAuthCookie(name, true);
var ticket = FormsAuthentication.Decrypt(cookie.Value);
var newTicket = new FormsAuthenticationTicket(
ticket.Version,
ticket.Name,
ticket.IssueDate,
ticket.Expiration,
true,
Newtonsoft.Json.JsonConvert.SerializeObject(userData),
ticket.CookiePath
);
var encTicket = FormsAuthentication.Encrypt(newTicket);
/// Use existing cookie. Could create new one but would have to copy settings over...
cookie.Expires = (rememberMe ? DateTime.Now.AddDays(62) : DateTime.MinValue);
cookie.Value = encTicket;
responseBase.Cookies.Set(cookie);
return FormsAuthentication.GetRedirectUrl(name, true /*This Is Ignored*/);
}
Admin
Now the admin does as it's told. Adds the cookie and redirects to an admin welcome screen.
Customer
The customer login area just isn't doing the same (see below screengrab).
It posts (as you can see it receives the request to save the cookie)
It redirects
But, oh no, the next request has no cookie
The system can't see the user is authenticated
Back to the login screen we go
I thought that the problem may be a local browser.
Nope, tried: different browsers, using private/incognito.
I thought it might be the setting of the cookie.
How can it be? They both use the same code.
Maybe web.config (in their respected directories)?
Nope, just <authorization> rules
Maybe a problem with the cookie?
Nope, looks fine. Same domain, HTTPS. all fine
Something to do with RememberMe?
Nope, tried both with and without
Soooo.... Been silly.
I forgot to exclude ([JsonIgnore]) a property that fetches some extra data (not needed for setting the cookie). This was being included and, obviously, made my cookie too large to save.
Oops.

.Net cookies keep coming back with expiration of zero

I am having trouble with the .Expires cookie attribute. It keeps coming back with 01/01/0001 12:00 AM, when I read the cookie back.
Here is the code. I added in the retrieve just below the save solely for debugging purposes. The save and retrieve happen in different places in the same file. I purposely did not specify a Domain, as I want the cookie to exist site wide.
The data shows up nicely, just not the expiration.
Note: I am testing under Visual Studio 2012 running under local host using .Net Framework 4.
System.Web.UI.Page oPage = this.Page;
HttpCookie oCookie = new HttpCookie("UserData");
// Set the cookie value.
oCookie.Secure = false;
oCookie["Field1"] = strField1;
oCookie["Field2"] = strField2;
oCookie.Expires = DateTime.Now.AddDays(1);
// Add the cookie.
oPage.Response.Cookies.Add(oCookie);
// Get the cookie.
oCookie = new HttpCookie("UserData");
oCookie = oPage.Request.Cookies["UserData"];
The browser will not send anything to the server except the cookie name and value. All of the other properties (expires, domain, path, httponly, ...) cannot be retrieved on requests after the cookie has been set.
The more accepted way to deal with this is to redirect the user to a login page when they try to access a protected resource and display some message along the lines of "You need to log in to view this page. If you were previously logged in, your session may have expired."
(Also note that you should be re-setting the cookie on every request, so that the user will not be logged out if they continue to use the site. It's not clear from your code whether you are doing this or not.)
I was just doing some more Google searching on my problem and saw this link, another posting here on Stackoverflow.
Cookies are always expired
I am also validating using the construct:
if (cookie != null && cookie.Expires > DateTime.Now)...
As several pointed out, expiration checking happens, if you can no longer retrieve the cookie. That is seriously dumb on whomever constructed this architecture. Yes, maybe there should be RequestCookie and ResponseCookie, the difference being ResponseCookie has no Expiry date.
The person who resopnded to me taught me that it is not just expires but other fields too.
In C# code, if using Form Authentication, You can find if cookie is persistent using below code
bool IsCookiePersistent = ((FormsIdentity)User.Identity).Ticket.IsPersistent;
Here Ticket will return the FormsAuthenticationTicket which has Expiration DateTime property.

Cookie expiration datetime and different date in client and server

I am using the following code for a custom "remember me" implimentation:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, member.UserName, DateTime.Now, DateTime.Now.AddHours(24), true, dataString);
string encTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
faCookie.Expires = ticket.Expiration;
HttpContext.Current.Response.Cookies.Add(faCookie);
But some users cannot login (Login page appears even after sign in).
It seems the problem is caused by the client having a different (greater) date than the server.
So, what is the best and correct solution for a "remember me" implementation.
To solve this problem I must remove this line:
faCookie.Expires = ticket.Expiration;
After removing this line, when user closes the browser, he must sign in (cookie is not persist).
What is the solution?
What you could do is get the clients Date/Time and use that for the Cookie, rather than the server time.
There is a great answer here showing you a good way to do this; basically populate a hidden field with the clients date/time and get it on postback.
You could have this hidden field on your masterpage so the clients date/time is always available. doesn't need to just be on the login screen.

how to remove cookies from browser in asp.net c#, SO answers NOT working

I'm trying to remove cookies using C# when a user logs out. The code suggestions listed here: remove cookies from browser do not work. I put several of them together in desperation and they are not working.
if (Request.Cookies["loginidcookie"] != null)
{
HttpCookie myCookie = new HttpCookie("loginidcookie");
myCookie.Value = String.Empty;
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Response.Cookies.Remove("loginidcookie");
}
Response.Redirect("logout.aspx");
So not only am I overwriting the value of the cookie with an empty string, I am setting it to expire yesterday AND removing it from the list of cookies. Yet when I run this code then hit the back button and reload, the cookie is still there with its original value. So how do I get rid of it?
Thank you
Try this instead:
string cookieName = "loginidcookie";
if (Request.Cookies[cookieName ] != null)
{
var myCookie = new HttpCookie(cookieName);
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Response.Redirect("logout.aspx", false);
Note (from here):
You cannot directly delete a cookie on a user's computer. However, you
can direct the user's browser to delete the cookie by setting the
cookie's expiration date to a past date. The next time a user makes a
request to a page within the domain or path that set the cookie, the
browser will determine that the cookie has expired and remove it.
You are adding the Cookie and then Removing it from the collection before the response is sent so you are effectively doing nothing.
HttpCookie myCookie = new HttpCookie("loginidcookie");
... and then below
Response.Cookies.Add(myCookie);
Response.Cookies.Remove("loginidcookie");
If you change the cookie to expire yesterday, you need to leave the cookie in the collection so that the browser takes care of deleting it once it sees the cookie has been updated with an expiration date in the past. In other words, don't call Response.Cookies.Remove("loginidcookie");
Try RedFilter's solution but use Server.Transfer() or Server.TransferRequest() instead of Response.Redirect() which it seems doesn't always let those cookie responses happen due to a possible bug.
Are you checking the cookie after closing the browser? Or reloading the page in the same browser?
If you are opening the page in the same browser you will see the cookie which is expired, but if you opened the new browser and try to access the page again, you would not get the cookie.

Automatically assign authentication token in .NET

I have implemented forms authentication with a .NET Membership Provider but I also want users to be able to login with Facebook. Once authenticated with Facebook, I want to automatically assign a .NET authentication token to the user. I have a HttpModule that is detecting the FB authentication but all my attempts to manually generate an authentication token have come up short.
I tried
FormsAuthentication.SetAuthCookie
FormsAuthentication.GetAuthCookie + Response.Cookies.Add
new FormsAuthenticationTicket(...) a la MSDN
In an HttpModule vs Page
Plus a few other desperate attempts. Nothing seems to work. How is this done?
Proposed way is using WIF
FormsAuthentication.Initialize();
// Create a new ticket used for authentication
FormsAuthentication.SetAuthCookie(UserName.Text, false);
// Create a new ticket used for authentication
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Ticket version
UserName.Text, // Username associated with ticket
DateTime.Now, // Date/time issued
DateTime.Now.AddMinutes(30), // Date/time to expire
false, // "true" for a persistent user cookie
"Admin", // User-data, in this case the roles
FormsAuthentication.FormsCookiePath);// Path cookie valid for
// Encrypt the cookie using the machine key for secure transport
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of auth cookie
hash); // Hashed ticket
// Set the cookie's expiration time to the tickets expiration time
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
// Add the cookie to the list for outgoing response
Response.Cookies.Add(cookie);
After you SetCookieAuth you need to do a redirect to give the HttpModule a chance to fire and set the HttpContext.User property.
It turns out someone else had registered another module in the solution that was interfering with HttpRequest and the authentication pieces. After I got rid of that, FormsAuthentication.SetAuthCookie(...) worked fine.
Thanks everyone for the help.

Categories

Resources