Create non-persistent cookie with FormsAuthenticationTicket - cookies

I'm having trouble creating a non-persistent cookie using the FormsAuthenticationTicket. I want to store userdata in the ticket, so i can't use FormsAuthentication.SetAuthCookie() or FormsAuthentication.GetAuthCookie() methods. Because of this I need to create the FormsAuthenticationTicket and store it in a HttpCookie.
My code looks like this:
DateTime expiration = DateTime.Now.AddDays(7);
// Create ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2,
user.Email,
DateTime.Now,
expiration,
isPersistent,
userData,
FormsAuthentication.FormsCookiePath);
// Create cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
cookie.Path = FormsAuthentication.FormsCookiePath;
if (isPersistent)
cookie.Expires = expiration;
// Add cookie to response
HttpContext.Current.Response.Cookies.Add(cookie);
When the variable isPersistent is true everything works fine and the cookie is persisted. But when isPersistent is false the cookie seems to be persisted anyway. I sign on in a browser window, closes it and opens the browser again and I am still logged in. How do i set the cookie to be non-persistent?
Is a non-persistent cookie the same as a session cookie? Is the cookie information stored in the sessiondata on the server or are the cookie transferred in every request/response to the server?

Try deleting:
if (isPersistent)
{ cookie.Expires = expiration; }
... and replacing it with:
if (!isPersistent) {
cookie.Expires = DateTime.Now.AddYears(-1); }

Related

Can you add a cookie to request with asp.net core middleware?

Am trying to write custom middleware in the ASP.net core pipeline, as part of my invoke, would like to append/add cookie, so then next middleware in the pipeline can access those cookie.
getting compiling error on set the cookie value. Can anyone recommend work around for this.
Note: When I tried with Response.Cookie , it works but only problem is, cookie is reflecting only on next request from the browser, but I need this to be reflecting on the next middleware in the pipeline immediately after execute this.
below code snippet
public async Task Invoke(HttpContext httpContext)
{
var queryParameters = httpContext.Request.Query;
var cookies = httpContext.Request.Cookies;
if (!cookies.ContainsKey(".AspNetCore.Session")
|| cookies[".AspNetCore.Session"] != "new_key")
{
httpContext.Request.Cookies[".AspNetCore.Session"] = "new_key";
}
await _next.Invoke(httpContext);
}
You cannot use cookie's value in same request. However, you could use good old HttpContext.Items.
public async Task InvokeAsync(HttpContext context)
{
context.Request.HttpContext.Items["key"] = "Hello!";
await _next(context);
}
You then retrieve it as
var value = HttpContext.Items["key"];
In my case I have an AuthorizationHandler that performs some checks to determine the user details and whether the user is logged in. The auth handler stores some of this info in a token in the request headers, so it can be easily accessed by the controllers.
When the user is logged in, this token can be read from the HttpContext.Request.Headers in a standard controller and all is well.
When the user is not logged in, the auth handler returns failure and so the request is redirected to "/login". Sadly the token header is not preserved across the redirect, so in my LoginController the token is null.
The only way I could make the token available to both a standard controller and LoginController is to store the token in both the request headers AND response cookies. This cookie can be read from the LoginController in the HttpContext.Request.Cookies collection. I set it to be short-lived as it's only needed briefly (it'll disappear after 5 seconds)
Here is part of the code from my auth handler:
HttpRequest request = _httpContextAccessor.HttpContext.Request;
HttpResponse response = _httpContextAccessor.HttpContext.Response;
request.Headers["X-Token"] = encryptedToken;
response.Cookies.Append("TokenCookie", encryptedToken, new CookieOptions
{
MaxAge = TimeSpan.FromSeconds(5),
Secure = true,
IsEssential = true,
});

How to set expiration date to client cookies?

I configured Identity Server:
public void Configuration(IAppBuilder app)
{
var factory = new IdentityServerServiceFactory().UseInMemoryClients(new Client[] {
new Client()
{
ClientName = "MyClient",
ClientId = "MyClientId",
Enabled = true,
Flow = Flows.Implicit,
RedirectUris = new List<string> { "MyClientServer/callback" },
};
});
}
and client server:
public void Configuration(IAppBuilder app)
{
var cookieOptions = new CookieAuthenticationOptions();
cookieOptions.AuthenticationType = "Cookies";
app.UseCookieAuthentication(cookieOptions);
var authenticationOptions = new OpenIdConnectAuthenticationOptions() {
Authority = "https://MyIdentityServer/core",
ClientId = "MyClientId",
SignInAsAuthenticationType = "Cookies",
UseTokenLifetime = true,
RedirectUri = "MyClientServer/callback"
});
app.UseOpenIdConnectAuthentication(authenticationOptions);
}
When user login with "Remember Me" option Identity cookie has expired date:
idsvr.session expires 04 October ...
But client cookie does not:
.AspNet.Cookies at end of session
What should I do to set the same expiration date to client cookie?
UPDATE:
I can set any expiration date in client application:
authenticationOptions.Provider = new CookieAuthenticationProvider()
{
OnResponseSignIn = (context) =>
{
var isPersistent = context.Properties.IsPersistent;
if (isPersistent) // Always false
{
context.CookieOptions.Expires = DateTime.UtcNow.AddDays(30);
}
}
};
But I cannot determine when to set expiration date. It should be set only when user selects "Remember Me", but IsPersistent option always false on client side.
The problem exists on simple boilerplate project too:
https://identityserver.github.io/Documentation/docsv2/overview/mvcGettingStarted.html
UPDATE2:
I need client cookie to be persistent because of bug in Safari - https://openradar.appspot.com/14408523
Maybe some workaround exists, so I can pass expiration date in callback from Identity to Client?
UPDATE3:
Actually, our Identity and Client servers have same parent domain like app.server.local and id.server.local. Maybe I can pass expiration date via additional cookie that belongs to parent domain (.server.local)? But I have no idea where it can be written on Identity, and where it can be applied on Client.
A cookie issued by IdentityServer and a cookie issued by a client application are not linked in any way. IdentityServer does not have any control over cookies in a client application.
When you log in to IdentityServer, you are issued a cookie that tracks the authenticated user within IdentityServer. This saves the user from entering their credentials for every client application, facilitating single sign on.
By default this cookie lasts for that session (so it expires once the browser closes), otherwise if you set "remember me" it will last for a set number of days, across sessions.
A cookie in a client application would be issued upon successful verification of an identity token from IdentityServer. This cookie can have any expiration time, any policy, any name. It's completely controlled by the client application. In your case client cookie expiration can be set in the CookieAuthenticationOptions in your client application.
You need to handle the cookie auth events. The open id middleware just creates an auth cookie, so you can handle all aspects of this cookie from those events. You'll need to look at the events and with a little trial and error you should be able to manage the cookie lifetime.
You can do it at the java-script by using following code in here I have created this cookie to expires within 14 days.
var exdate = new Date();
exdate.setDate(exdate.getDate() + 14);
document.cookie = "yourcookie=" + yourCookieValue + ";expires=" + exdate.toUTCString() + ";";

Struts2 Remove Cookies when user logs out

I am trying to make my application to remove the cookies that are set, so whenever the user clicks logout, the cookies are removed. I set my cookies like this, with the CookieProvider.
public Set<Cookie> getCookies(){
Set<Cookie> cookies = new HashSet<>();
Cookie name = new Cookie("name", userInfo.getName() );
name.setMaxAge(60*60*24*365);
name.setPath("/");
cookies.add(name);
}
I do remove the user from the sessionMap whenever the user clicks on logout. Like this:
public String execute() throws Exception{
sessionMap.remove("userId");
return SUCCESS;
}
Is there a simple way of also removing the cookies in Struts2 whenever the user logs out?

HTTPOnly Cookie not being stored before redirect

Currently, I have an HTML page that sends a POST request to a Python server with login details. The Python server verifies the login and then sends back a cookie via headers (I'm using the Cookie class built into the Python library). I want to redirect as soon as I get a 200 OK status. The issue is that the cookies are not being set quickly enough, so the redirect happens before the cookies are set and thus the check_login page will display that I have not logged in.
I want the browser to store an HTTPOnly cookie. Is there something in the XMLHttpRequest API that will let me redirect after the cookie has been stored, or an alternative method?
Thanks!
The HTTPRequest code:
var httpRequest = new XMLHttpRequest();
var url = 'http://localhost/login/';
httpRequest.onreadystatechange = function(){
if (httpRequest.readyState == 4) {
if(httpRequest.status == 200) {
window.location = "http://localhost/check_login/";
}
};
httpRequest.open("POST", url,false);
httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
httpRequest.send(/*login details*/);
This request is called by clicking a button. If I go back to the page that this button is on and then click it again, I will always be logged in because the cookie was already set from the first click.

How can I get HttpOnly cookies in Windows Phone 8?

I am working in a Windows Phone 8 PCL project. I am using a 3rd party REST API and I need to use a few HttpOnly cookies originated by the API. It seems like getting/accessing the HttpOnly cookies from HttpClientHandler's CookieContainer is not possible unless you use reflection or some other backdoor.
I need to get these cookies and send them in subsequent requests otherwise I am not going to be able to work with this API - how can I accomplish this? Here is what my current request code looks like:
Thanks in advance.
//Some request
HttpRequestMessage request = new HttpRequestMessage();
HttpClientHandler handler = new HttpClientHandler();
//Cycle through the cookie store and add existing cookies for the susbsequent request
foreach (KeyValuePair<string, Cookie> cookie in CookieManager.Instance.Cookies)
{
handler.CookieContainer.Add(request.RequestUri, new Cookie(cookie.Value.Name, cookie.Value.Value));
}
//Send the request asynchronously
HttpResponseMessage response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
//Parse all returned cookies and place in cookie store
foreach (Cookie clientcookie in handler.CookieContainer.GetCookies(request.RequestUri))
{
if (!CookieManager.Instance.Cookies.ContainsKey(clientcookie.Name))
CookieManager.Instance.Cookies.Add(clientcookie.Name, clientcookie);
else
CookieManager.Instance.Cookies[clientcookie.Name] = clientcookie;
}
HttpClient httpClient = new HttpClient(handler);
The HttpOnly cookie is inside the CookieContainer, it's only that is not exposed. If you set the same instance of that CookieContainer to the next request it will set the hidden cookie there (as long as the request is made to the same site the cookie specifies).
That solution will work until you need to serialize and deserialize the CookieContainer because you are restoring state. Once you do that you lose the HttpOnly cookies hidden inside the CookieContainer. So, a more permanent solution would be using Sockets directly for that request, read the raw request as a string, extract the cookie and set it to the next requests. Here's the code for using Sockets in Windows Phone 8:
public async Task<string> Send(Uri requestUri, string request)
{
var socket = new StreamSocket();
var hostname = new HostName(requestUri.Host);
await socket.ConnectAsync(hostname, requestUri.Port.ToString());
var writer = new DataWriter(socket.OutputStream);
writer.WriteString(request);
await writer.StoreAsync();
var reader = new DataReader(socket.InputStream)
{
InputStreamOptions = InputStreamOptions.Partial
};
var count = await reader.LoadAsync(512);
if (count > 0)
return reader.ReadString(count);
return null;
}
There is also a second possibility - to manually go through response headers, grab and then parse Set-Cookie headers using a bunch of custom code.
It looks something like that, when you are going to match and save a single PHPSESSID cookie (assume LatestResponse is your HttpResponseMessage containing website response):
if (LatestResponse.Headers.ToString().IndexOf("Set-Cookie:") != -1) try
{
string sid = LatestResponse.Headers.ToString();
sid = sid.Substring(sid.IndexOf("Set-Cookie:"), 128);
if (sid.IndexOf("PHPSESSID=") != -1)
{
settings.Values["SessionID"] = SessionID = sid.Substring(sid.IndexOf("PHPSESSID=") + 10, sid.IndexOf(';') - sid.IndexOf("PHPSESSID=") - 10);
handler.CookieContainer.Add(new Uri("http://example.com", UriKind.Absolute), new System.Net.Cookie("PHPSESSID", SessionID));
}
} catch (Exception e) {
// your exception handling
}
Note this code inserts the cookie to CookieContainer for that object's life unless manually deleted. If you want to include it in a new object, just pull the right setting value and add it to your new container.