Are session and cookies the same thing? - asp.net

Since session and cookies are both used to store temporary data, what is the difference between them?

As for may knowledge:
If you set the variable to "cookies", then your users will not have to log in each time they enter your community.
The cookie will stay in place within the user’s browser until it is deleted by the user.
But Sessions are popularly used, as the there is a chance of your cookies getting blocked if the user browser security setting is set high.
If you set the variable to "sessions", then user activity will be tracked using browser sessions, and your users will have to log in each time they re-open their browser. Additionally, if you are using the "sessions" variable, you need to secure the "sessions" directory, either by placing it above the web root or by requesting that your web host make it a non-browsable directory.
The Key difference would be cookies are stored in your hard disk whereas a session aren't stored in your hard disk. Sessions are basically like tokens, which are generated at authentication. A session is available as long as the browser is opened.
hope following links will further clarifying your doubts
http://wiki.answers.com/Q/What_is_the_difference_between_session_and_cookies
http://www.allinterview.com/showanswers/74177.html

Cookies store a user's data on their computer.
Session implementations store a user's temporary data on a server (or multiple servers, depending on the configuration).

In each HTTP response, the server has the opportunity to add a header Set-Cookie: {cookie-name}={cookie-data}; {cookie-options}.
The browser will, in every subsequent HTTP request (or as specified by the options), add a header Cookie: {cookie-name}={cookie-data}.
Request #1:
POST /auth/login HTTP/1.1
Host: www.example.com
username=Justice&password=pass1234
Response #1:
HTTP/1.1 307 Temporary Redirect
Set-Cookie: user_id=928
Location: http://www.example.com/dashboard
Request #2:
GET /dashboard HTTP/1.1
Host: www.example.com
Cookie: user_id=928
Response #2:
HTTP/1.1 200 OK
Content-Type: text/html
<html>
<head>...</head>
<body>...</body>
</html>
All future requests will also include the Cookie header.

Cookies are stored on the client as either small text files on the files system (persistent cookies) or in the browsers memory (non-persistent cookies) and passed to the server and returned to the client with each request and response. Persistent cookies will still be available between browser sessions as long as the expiry date has not passed. Non-persistent cookies will be lost once the browser is closed.
Session is stored on the server in memory. Cookies are very often used as a way of preserving the reference to the users session between requests however this can also be done with querystring parameters if cookies are disabled on a clients browser.

A cookie is client side a session is server side

Sessions are stored server side. You can have inproc sessions, which will be stored in memory, or you can store the sessions in an SQL database. You can read more here.
Cookies are stored on the client's computer. This means that it's not recommended to store important details in a cookie, because clients could easily manipulate them.

Cookies are a small text file stored on the client that can hold domain specific information,
a session is held server side in either memory, a database or a seperate server and keyed via a session key, they are meant only to persist for a 'session' where as a cookie can persist for a length of time or indefinately therefore being usable in multiple sessions.

They are not the same thing. A Session is a concept whereby the state of a single user's browsing session is stored.
Cookies are a good means of implementing this concept, thus the widespread practice of "Session cookies".

The main difference between data stored in session and cookies is that data stored in session is stored on the server side (user can't operate on such data), while cookies are stored on a client side. They might be manipulated somehow by user. If you have a really sensitive data - then store it in session. But all other data you can store in cookies not to overload the server.

Related

Nginx: allow only certain cookies in http response

I'm using playframework and nginx. playframework may add following cookies to http response: PLAY_SESSION, PLAY_FLASH, PLAY_LANG.
I want to make sure that only above cookies (PLAY_*) are allowed in nginx level. If there are other cookies (let's say they're added accidentally) they should be removed by nginx.
How can I allow only predefined cookies in http response in nginx?
PS: If it's not possible to solve this issue in nginx, I need to fix by using playframework.
How cookies work?
First, let's establish what's cookies — they're little pieces of "sticky" hidden information that lets you keep state on your web-site for a given User-Agent. These cookies are often used for tracking users, keeping session and storing minor preference information for the site.
Set-Cookie HTTP response header (from server to client)
Cookies can be set by the server through the Set-Cookie response header (with a separate header for each cookie), or, after the page has already been transferred from the server to the client, through JavaScript.
Note that setting cookies is a pretty complex job — they have expiration dates, http/https settings, path etc — hence the apparent necessity to use a separate Set-Cookie header for each cookie.
This requirement to have a separate header is usually not an issue, since cookies aren't supposed to be modified all that often, as they usually store very minimal information, like a session identifier, with the heavy-duty information being stored in an associated database on the server.
Cookie HTTP request header (from client to server)
Regardless how they were first set, cookies would then included in eligible subsequent requests to the server by the client, using the Cookie request header, with a whole list of eligible cookies in one header.
Note that, as such, these cookies that are sent by the client back to the server is a simple list of name and attribute pairs, without any extra information about the underlying cookies that store these attributes on the client side (e.g., the expiration dates, http/https setting and paths are saved by the client internally, but without being revealed in subsequent requests to the server).
This conciseness of the Cookie request header field is important, because, once set, eligible cookies will be subsequently included in all forthcoming requests for all resources with the eligible scheme / domain / path combination.
Caching issues with cookies.
The normal issue of using cookies, especially in the context of acceleration and nginx, is that:
cookies invalidate the cache by default (e.g., unless you use proxy_ignore_headers Set-Cookie;),
or, if you do sloppy configuration, cookies could possibly spoil your cache
e.g., through the client being able to pass cookies to the upstream in the absence of proxy_set_header Cookie "";,
or, through the server insisting on setting a cookie through the absence of proxy_hide_header Set-Cookie;.
How nginx handles cookies?
Cookie from the client
Note that nginx does support looking through the cookies that the client sends to it (in the Cookie request header) through the $cookie_name scheme.
If you want to limit the client to only be sending certain cookies, you could easily re-construct the Cookie header based on these variables, and send only whichever ones you want to the upstream (using proxy_set_header as above).
Or, you could even make decisions based on the cookie to decide which upstream to send the request to, or to have a per-user/per-session proxy_cache_key, or make access control decisions based on the cookies.
Set-Cookie from the backend
As for the upstream sending back the cookies, you can, of course, decide to block it all to considerably improve the caching characteristics (if applicable to your application, or parts thereof), or fix up the domain and/or path with proxy_cookie_domain and/or proxy_cookie_path, respectively.
Otherwise, it's generally too late to make any other routing decision — the request has already been processed by the selected upstream server, and the response is ready to be served — so, naturally, there doesn't seem to be a way to look into these individual Set-Cookie cookies through normal means in nginx (unless you want to go third-party modules, or lua, or perl), since it'd already be too late to make any important routing decisions for a completed request.
Basically, these Set-Cookie cookies have more to do with the content than with the way it is served or routed, so, it doesn't seem appropriate to have integrated functionality to look into them through nginx.
(If you do need to make routing decisions after the completion of the request, then nginx does support X-Accel-Redirect, as well as some other special headers.)
If your issue is security, then, as I've pointed out above, the upstream developer can already use JavaScript to set ANY extra cookies however they want, so, effectively, trying to use nginx to limit some, but not all, Set-Cookie responses from the server is kind of a pointless endeavour in the real world (as there is hardly any difference between the cookies set through JavaScript compared to Set-Cookie).
In summary:
you can easily examine and reconstruct the Cookie header sent by the client to the server before passing it over to the backend, and only include the sanctioned cookies in the request to upstream backend,
but, unless you want to use lua/perl, or have your own nginx module (as well as possibly quarantine the JavaScript from the pages you serve), then you cannot pass only certain Set-Cookie headers back from the upstream backend to the client with a stock nginx.conf — with the Set-Cookie headers, it's an all-or-nothing situation, and there doesn't seem to be a good-enough use-case for a distinct approach.
For an Nginx solution it might be worth asking over at serverfault. Here is a potential solution via Play Framework.
package filters
import javax.inject._
import play.api.mvc._
import scala.concurrent.ExecutionContext
#Singleton
class ExampleFilter #Inject()(implicit ec: ExecutionContext) extends EssentialFilter {
override def apply(next: EssentialAction) = EssentialAction { request =>
next(request).map { result =>
val cookieWhitelist = List("PLAY_SESSION", "PLAY_FLASH", "PLAY_LANG")
val allCookies = result.newCookies.map(c => DiscardingCookie(c.name))
val onlyWhitelistedCookies = result.newCookies.filter(c => cookieWhitelist.contains(c.name))
result.discardingCookies(allCookies: _*).withCookies(onlyWhitelistedCookies: _*)
}
}
}
This solution utilizes Filters and Result manipulation. Do test for adverse effects on performance.

Routes using cookie authentication from previous version of Paw no longer work on new version

I have a route that uses an authentication cookie set by another route. I've created it like this:
This method no longer works in the new version. Paw complains that there is no set-cookie header in the response from the Authenticate request.
It seems this is because Paw now takes the cookies and handles them differently from other headers. I like this approach because it should make this sort of authentication easier, but, unfortunately, it's not working like I would expect.
Here's how I have configured a newer request:
So, I've set the cookie header to the Response Cookies dynamic value which, I believe, should pass along the cookies set previously. I would think I should select the Authenticate request from the dropdown (since it's the response from this request that actually sets the cookie, but the cookie value disappears if I do that. Instead, I have left the request value as Current Request since that seems to contain the correct value.
I've also noticed the Automatically send cookies setting which I thought might be an easy solution. I removed the manual cookie header from my request leaving this checked in hopes it might automatically send over any cookies from the cookie jar along with the request, but that doesn't seem to work either. No matter what I try, my request fails to produce the desired results because of authentication.
Can you help me understand how to configure these requests so that I can continue using Paw to test session-authenticated routes?
Here are a couple of things that will make you understand how cookies work in Paw (starting from version 2.1):
1. Cookies are stored in Jars
To allow users to keep multiple synchronous sessions, cookies are stored in jars, so you can switch between sessions (jars) easily.
Cookies stored in jars will be sent only if they match the request (hostname, path, is secure, etc.).
2. Cookies from jars are sent by default, unless Cookie header is overridden
If you set a Cookie header manually, cookies stored in jars wont' be sent.
And obviously unless Automatically Send Cookies is disabled.
3. The previous use of "Response Headers" was hacky. Use Response Cookies.
In fact, Set-Cookie (for responses) and Cookie (for requests) have different syntaxes. So you can't send back the original value of Set-Cookie (even though it seemed to be working in most cases).
The new Response Cookies dynamic value you mentioned has this purpose: send back the cookies set by a specific request.
Now, in your case, I would use a Response Cookies dynamic value all the time. As you have only 1 request doing auth / cookie setting, it might be the easiest to handle. Also, maybe check Ignore Domain, Path, Is Secure and Date to make sure your cookie is always sent even if you switch the host (or something else).
Deleting the cookies in the cookie jar and hitting the authentication endpoint again seems to have fixed the problem. Not sure why, but it seems to be working now either manually sending a cookie or using the Automatically send cookies setting.

How does ASP.NET identify a request and match it to a previous server side session?

How does ASP.NET identify a request and match it to a previous server side session?
E.G:
Client sends first request, server side, setups a session variable. (e.g loggedIn)
Request two comes in, how does the server match this request to the session it created last time? (e.g mac address, ip address etc.)?
I am interested in how this is secure.
There are two basic ways: a cookie and uri.
In a cookie mode, the ASPNET_SessionId cookie is appended to the very first response. The id can change but stays the same as soon as first item is put into the session. You can change the name of the cookie.
In a cookieless mode, the uri gets modified and the session id becomes part of it. Instead of http://foo.bar/qux you have http://foo.bar/(sessionid)/qux
Both modes are handled automatically depending on the configuraion (web.config, session section).
The security mostly depends on a secure channel. The cookie/url can be sniffed and reused if transmitted over unencrypted wire.

HTTP Session Tracking

Since HTTP is a stateless protocol, when a client makes a number of requests to the server, how does the server uniquely identify a particular client's requests over a period of time say t1, t2, t3..
I browsed the web and came across terms like session id, URL rewriting and cookies. But it would be great if someone explains it in a better way. Specifically which part of the HTTP request and response would be used for session tracking?
As you mentioned, common ways to implement HTTP session tracking include URL rewriting and cookies. Session tracking basically requires that a session ID is maintained across multiple requests to the server. This means that each time a given client makes a request to the server, it passes the same session ID. The server can use this ID to lookup the session information it maintains.
When using cookies, the server asks the client to store a cookie by setting the Set-Cookie HTTP response header. This cookie contains the unique session ID assigned to that client - in this example the string 'ABAD1D':
Set-Cookie: JSESSIONID=ABAD1D;path=/
The cookie is then sent back to the server by the client using the Cookie HTTP request header on each request and thus the server is informed on each request the session ID currently assigned to the client.
Cookie: JSESSIONID=ABAD1D
When using URL rewriting, this same session ID is instead sent somewhere in the URL. Again, the server extracts the session ID from the URL so that it can lookup the session for a particular client:
http://my.app.com/index.jsp;JSESSIONID=ABAD1D
However, the server must also make sure that any URLs in the web pages sent back to the client are also rewritten to contain that particular clients session ID. As the session ID is encoded in the URLs, this method of session tracking is transparent to the browser. Often a server will resort to URL rewriting if it finds it is unable to set a session cookie on the client - implying that the client does not support/allow cookies.
Note that sessions can expire. This means that if the server does not 'see' a given session ID for a period of time, it may remove the session data to preserve resources.
Specifically which part of the HTTP
request and response would be used for
session tracking?
In the HTTP response, the server can set a cookie. It does so with the Set-Cookie header. For example:
Set-Cookie: session=12345; path=/
The client then returns the value of all cookies that match the properties that were set along with the cookie, which can include path (as above) and domain, and that haven't expired yet.
The cookie is sent back to the server as part of the HTTP headers. For example:
Cookie: session=12345
None of the original property information is sent back with the cookie.
A unique cookie allows the server to associate a unique key with a particular browser instance. The server can then use that key as an index into a hash table or a database table that holds unique per-user state information.
Session tracking is a server side thing.
A web server issues some session identifier that is returned to the browser. Browser submits this session identifier along with each request.
This is probably done using cookies transparently for the user.
the session handling is in most case handled by sending a cookie to the client. that cookie would be sent back to the server on every request from that particular client.
The session id will be associated with some resources on server side (file,ram space) so the server by reading the session id in the cookie can find this resource and then know which client it was.
Find enough details here
HTTP Sessions are the recommended approach. A session identifies the requests that originate from the same browser during the period of conversation. All the servlets can share the same session. The JSESSIONID is generated by the server and can be passed to client through cookies, URL re-writing (if cookies are turned off) or built-in SSL mechanism. Care should be taken to minimize size of objects stored in session and objects stored in session should be serializable. In a Java servlet the session can be obtained as follows:
HttpSession session = request.getSession(); //returns current session or a new session
Sessions can be timed out (configured in web.xml) or manually invalidated.
HTTP Session allows web servers to maintain user identity and store user specific data during multiple request/response between client and we application

Is a Session ID generated on the Server-side or Client-side?

This web page http://www.w3schools.com/ASP/prop_sessionid.asp states that a session ID is generated on the ServerSide.
If this is the case, then how does a server know it's still the same client on the 2nd request response cycle?
Surely the SessionId would be generated on the ClientSide so that the client would be sure of passing the same value to the server?
The SessionID is generated Server Side, but is stored on the Client within a Cookie. Then everytime the client makes a request to the server the SessionID is used to authenticate the existing session for the client.
The session ID is normally generated on the server. It's then sent to the client, either as a cookie in the HTTP headers, or by including it in the HTML, i.e. the links become href=my.html?sessionid=1234.
The client's next request will then contain the session Id, either in the cookie or the GET part of the request.
The server will generate a session id if none exists. But once it has been generated, the client can pass that id back to the server. If the client modifies that id, you would likely get an error from the server, and a new id generated.
The ID is generated on the server. The client then stores this in a session cookie that the server picks up on subsequent request.
If the server is running in cookie-less mode, then the session key becomes part of the URL and the server parses it from there.
ADDED: ...and if the server is expecting to use a session cookie but the client has cookies disabled, then from the perspective of the server, all requests are new sessions as it cannot tell that this is the same user.

Resources