ASP.NET cookie not written? Redirect issue? - asp.net

I have the following code:
var serializer = new XmlSerializer(typeof(classes.Member));
TextWriter writer = new StringWriter();
serializer.Serialize(writer, active_resident);
HttpCookie cookie = Request.Cookies["ActiveUser"];
if (cookie == null)
{
cookie = new HttpCookie("ActiveUser");
}
cookie.Expires = DateTime.Now.AddHours(1);
cookie.Value = Genesis.Encryption.EncryptAES(writer.ToString(), Genesis.Generic.ReadAppSettingsValue("GenesisEncryptionKey"));
Response.Cookies.Add(cookie);
writer.Close();
// Redirect to Secure Area
Response.Redirect("secure/dashboard.aspx", false);
Strangely, the cookie is not written? However, the ASP.Net Session cookie is? Any ideas?

Related

unable to delete or remove single sign on cookie in asp.net mvc

string[] myCookies = Request.Cookies.AllKeys;
foreach (string cookie in myCookies)
{
Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
}
if (Request.Cookies["UserSettings"] != null)
{
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}

ASP.NET Formauthentication.Signout() not working

I am using forms authentication for a web site I am building and it works out pretty well except I cannot get the auth cookie to delete or expire. I have tried any number of methods and none of them seem to work. Here is what I create the cookie.
FormsAuthentication.SetAuthCookie(model.userName, false);
HttpCookie cookie = new HttpCookie("user");
Response.Cookies["user"].Value = model.userName;
Now the second cookie isn't an actual authcookie, that is used for some of the inner workings of the site per client request. This next part are various things I have tried to delete the cookie.
FormsAuthentication.SignOut();
Roles.DeleteCookie();
Session.Clear();
//Response.Cache.SetExpires(DateTime.Now);
//foreach (var cookie in Request.Cookies.AllKeys)
//{
// Request.Cookies.Remove(cookie);
//}
//foreach (var cookie in Response.Cookies.AllKeys)
//{
// Response.Cookies.Remove(cookie);
//}
//Session.Abandon();
//// clear authentication cookie
HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
cookie1.Path = FormsAuthentication.FormsCookiePath;
cookie1.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie1);
HttpCookie cookie = Request.Cookies["user"];
string userName = cookie.Value;
cookie.Expires.AddDays(-30);
//HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
//cookie2.Expires = DateTime.Now.AddYears(-1);
//Response.Cookies.Add(cookie2);
//HttpCookie cookie = Request.Cookies["user"];
//cookie.Expires = DateTime.Now.AddDays(-1d);
//HttpCookie user = Request.Cookies["user"];
//role.Expires = DateTime.Now.AddDays(-1d);
//Response.Cookies["user"].Value = null;
Session.Abandon();
I just cut and paste the entire thing in there, some of it is commented out now but at some point and time I have attempted to use each method in that code to remove the cookie. Some of these attempts were just guesses since I have been at this for a while. Last here is the auth section of my web.config
<authentication mode="Forms" >
<forms loginUrl="~/login" timeout="90" name=".ASPXFORMS" />
</authentication>
Any input as to what I am doing wrong is appreciated.
Try calling
FormsAuthentication.SignOut()
Before calling session. I generally place this in a separate method to make it easy to call from multiple places. Something like this:
internal void SignOut(HttpContext context)
{
FormsAuthentication.SignOut();
HttpSessionState session = context.Session;
if(session != null)
{
session.Abandon();
}
}

aspnet auth cookie twice in Request

I'm dealing with custom authentication cookie in AspNet web app.
Using asp:Login component, here is how user is authenticated:
void L_Authenticate(object sender, AuthenticateEventArgs e)
{
if (L.UserName == "john" && L.Password == "cookie")
{
FormsAuthenticationTicket ticket =
new FormsAuthenticationTicket(1, "john",
DateTime.Now,
DateTime.Now.AddSeconds(30),
false, "");
var cookieConnexion = new HttpCookie("myCookie");
cookieConnexion.Value = FormsAuthentication.Encrypt(ticket);
cookieConnexion.Expires = ticket.Expiration;
this.Response.Cookies.Set(cookieConnexion);
Z.Text = "<a href='/Prive/Home.aspx'>next</a>";
}
}
First of all, I don't set e.Authenticated = true or .ASPXAUTH cookie will be created. I don't want that. Second, I don't do Response.Redirect.
Now, in Global.asax, User is set in current HttpContext:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
}
else
{
var cookie = this.Request.Cookies["myCookie"];
if (cookie != null)
{
var ticket = FormsAuthentication.Decrypt(cookie.Value);
if (ticket != null)
{
HttpContext.Current.User =
new ClientRolePrincipal(new GenericIdentity(ticket.Name));
ticket = new FormsAuthenticationTicket(1, ticket.Name,
DateTime.Now,
DateTime.Now.AddSeconds(30),
false, ticket.UserData);
cookie.Value = FormsAuthentication.Encrypt(ticket);
cookie.Expires = ticket.Expiration;
this.Response.Cookies.Set(cookie);
}
}
}
}
First request to the app (using chrome dev tools, I track down cookies in request/responses headers):
0 cookie in request
0 cookie in response: ASP.NET_SessionId
User logs in:
1 cookie in request: ASP.NET_SessionId
1 cookie in response: myCookie
User browses to Home.aspx:
2 cookies in request: ASP.NET_SessionId, myCookie
1 cookie in response: myCookie (renewed)
OK.
Now, if on PreRender I display elements contained in this.Request.Cookies, I see twice myCookie. Why?
ASP.NET_SessionId, domain '' , path '/', value = nk1cy255quh32o45hxtg4x55
myCookie, domain '' , path '/', value = BF6246B7E5A5100AA59A7B7237B446...
myCookie, domain '' , path '/', value = BF6246B7E5A5100AA59A7B7237B446...

Cookie is the same from two different browser machine clients

I have two browsers from two different machines hitting a test page. The test page is retrieving a cookie. If one is not there, it creates a cookie.
public string GetUserCookieId()
{
string cookieName = "CookieId3";
HttpCookie userInfoCookies = Request.Cookies[cookieName];
string cookieId = "";
if (userInfoCookies != null)
cookieId = userInfoCookies.Value;
if (string.IsNullOrEmpty(cookieId))
{
cookieId = Guid.NewGuid().ToString();
HttpCookie cookie = new HttpCookie(cookieName);
cookie.Value = cookieId;
cookie.Expires = DateTime.Now.AddDays(90);
Response.SetCookie(cookie);
}
return cookieId;
}
Both browser machines are displaying the same cookie value on the page. This even once I have renamed the cookie to "CookieId3". Please tell me where i am going wrong.
As you can see, the method is not static. Thank you
The issue appears to be the difference between Request and HttpContext.Current.Request when the code is accessed from a ClassLibrary.
Is anyone is able to shed some light on this?!
The following works.
public string GetUserCookieId()
{
string cookieName = "CookieId18";
HttpCookie userInfoCookies = HttpContext.Current.Request.Cookies[cookieName];
string cookieId = "";
if (userInfoCookies != null)
cookieId = userInfoCookies.Value;
if (string.IsNullOrEmpty(cookieId))
{
cookieId = Guid.NewGuid().ToString();
HttpCookie cookie = new HttpCookie(cookieName);
cookie.Value = cookieId;
cookie.Expires = DateTime.Now.AddDays(90);
HttpContext.Current.Response.SetCookie(cookie);
}
return cookieId;
}

Problem creating persistent authentication cookie: ASP.NET MVC

OK, here's my code to create an authentication cookie:
// get user's role
List<UserType> roles = rc.rolesRepository.GetUserRoles(rc.userLoginRepository.GetUserID(userName));
List<string> rolesList = (from r in roles
select r.ToString()).ToList();
string[] rolesArr = rolesList.ToArray();
// create encryption cookie
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
userName,
DateTime.Now,
DateTime.Now.AddDays(90),
createPersistentCookie,
String.Join(";",rolesArr) //user's roles
);
// add cookie to response stream
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
//FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
And here's my code in Global.asax to set the user roles into the user identity:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null || authCookie.Value == "")
{
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
string[] roles = authTicket.UserData.Split(new char[] { ';' });
if (Context.User != null)
{
Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);
}
}
catch
{
return;
}
}
However, if "createPersistentCookie" is TRUE in the top example, no persistent cookie is created. If I uncomment the last line like so:
//System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
then the persistent cookie is created on my hard drive. BUT then in the Global.asax code, the UserData field in "authTicket" is blank, so I can't set up the roles properly!
So I have to use SetAuthCookie to create a persistent cookie, but then for some reason the UserData field disappears from the persistent cookie.
What is the answer to this??
To create a persistent cookie you need to set the Expires property:
if (authTicket.IsPersistent)
{
authCookie.Expires = authTicket.Expiration;
}

Resources