session and cookie management in .net

16
Session and Cookie Session and Cookie Management in .Net Management in .Net Sandeep Kiran Shiva Sandeep Kiran Shiva UIN: 00822389 UIN: 00822389

Upload: penney

Post on 13-Jan-2016

39 views

Category:

Documents


0 download

DESCRIPTION

Session and Cookie Management in .Net. Sandeep Kiran Shiva UIN: 00822389. State Management Overview. New instance of the Web page class is created each time the page is posted to the server. Http is a stateless protocol! ASP.NET options for State Management: Client Based : View state - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Session and Cookie Management in .Net

Session and Cookie Session and Cookie Management in .NetManagement in .Net

Sandeep Kiran ShivaSandeep Kiran ShivaUIN: 00822389UIN: 00822389

Page 2: Session and Cookie Management in .Net

State Management State Management OverviewOverview

•New instance of the Web page class is created each time the page is posted to the server.•Http is a stateless protocol!

•ASP.NET options for State Management:

Client Based :•View state•Control state•Hidden fields•Cookies•Query strings

Server Based:•Application state•Session state•Profile Properties

Page 3: Session and Cookie Management in .Net

Cookies-IntroductionCookies-Introduction

• A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The cookie contains information the Web application can read whenever the user visits the site.

•A cookie consists of one or more  name-value pairs  containing bits of information, which may be encrypted for information privacy and data security purposes.

•Uses: Authentication, Session tracking (state maintenance), Storing site preferences,  Shopping cart contents, The identifier for a server-based session, Anything else that can be accomplished through storing textual data.

Page 4: Session and Cookie Management in .Net

Write a Cookie:

Response.Cookies["userName"].Value = "patrick"; Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1); >>Here, the values of the Cookies() collection are set directly.

HttpCookie aCookie = new HttpCookie("lastVisit"); aCookie.Value = DateTime.Now.ToString(); aCookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(aCookie);>>Here, the code creates an instance of an object of type HttpCookie

Read a Cookie:

if(Request.Cookies["userName"] != null) Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);

if(Request.Cookies["userName"] != null) { HttpCookie aCookie = Request.Cookies["userName"]; Label1.Text = Server.HtmlEncode(aCookie.Value); }

Page 5: Session and Cookie Management in .Net

Delete a Cookie:

HttpCookie aCookie; string cookieName; int limit = Request.Cookies.Count; for (int i=0; i<limit; i++) {

cookieName = Request.Cookies[i].Name; aCookie = new HttpCookie(cookieName); aCookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(aCookie);

}

Cookie Scope:

HttpCookie appCookie = new HttpCookie("AppCookie"); appCookie.Value = "written " + DateTime.Now.ToString(); appCookie.Expires = DateTime.Now.AddDays(1); appCookie.Path = "/Application1"; Response.Cookies.Add(appCookie);

Page 6: Session and Cookie Management in .Net

Drawbacks:•Cookie Hijacking: Cookie theft is the act of intercepting cookies by an

unauthorized party.

This issue can be overcome by securing the communication between the user's computer and the server by employing Transport Layer Security (https protocol) to encrypt the connection and using a secure flag.

•Cross-site Scripting: making the browser itself send cookies to malicious servers that should not receive them. Encrypting cookies before sending them on the network does not help against this attack

A way for preventing such attacks is by using the HttpOnly flag

Page 7: Session and Cookie Management in .Net

Sample code:Sample code:public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Request.Cookies["id"] != null) { string userId = Request.Cookies["id"].Value; Response.Write("User Id value" + userId); } HttpCookie cookie = Request.Cookies["user"]; // for safety, always check for NULL. If cookie doesn't exist, it will be NULL if (cookie != null) { string name = cookie["name"]; string age = cookie["age"]; lblCookieExistance.Text += "Multi-valued Cookie exist<br>"; lblCookieExistance.Text += string.Format("Name : {0}<br>Age : {1}", name, age); } else lblCookieExistance.Text = "Cookie not exist"; }

protected void CreateCookieClicked(object sender, EventArgs e) { Response.Cookies["id"].Value = "10"; Response.Cookies["id"].Expires = DateTime.Now.AddDays(1); }

Page 8: Session and Cookie Management in .Net

protected void btnRemoveCookie_Click(object sender, EventArgs e) { Response.Cookies["id"].Expires = DateTime.Now.AddDays(-1); lblMessage.Text = "Cookie deleted. Try opening the same page in another

window of the same browser"; } protected void btnCreateMultiValuedCookie_Click(object sender, EventArgs e) { HttpCookie cookie = new HttpCookie("user"); cookie["name"] = "Foo"; cookie["age"] = "22"; cookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(cookie); lblMessage.Text = "Cookie created“; }}

Demo …..

Page 9: Session and Cookie Management in .Net

Sessions- IntroductionSessions- Introduction•ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application.

Fig : For every client session data store separately

Page 10: Session and Cookie Management in .Net

Advantages Of Sessions:•It helps to maintain user states and data to all over the application.•It can easily be implemented and we can store any kind of object. •Stores every client data separately. •Session is secure and transparent from user.•Session variables allow for customization of a web site.

Disadvantages:•Performance overhead in case of large volume of user, because of session data stored in server memory.•The overuse of Session variables can lead to very unreadable and unmaintainable code.

Page 11: Session and Cookie Management in .Net

Session Variables:•used to store data about the current user and his session.

•Storing values in Session Variables:Session["FirstName"] = FNameTB.Text; Session["LastName"] = LNameTB.Text;

•Retrieving values  from Session Variables://Check weather session variable is null or not if (Session["DataSet"] != null) { //Retrieving Dataset from Session

MyDs = (DataSet)Session["DataSet"]; } Else {

//Do Something else }

Page 12: Session and Cookie Management in .Net

Session ID:

•Asp.Net use 120 bit identifier to track each session.•When client communicate with server, only session id is transmitted.•When client request for data, ASP.NET looks on to session ID and retrieves corresponding data.

Page 13: Session and Cookie Management in .Net

Method Description

Session.Remove(strSessionName); Remove an Item from Session State Collection

Session.RemoveAll() Remove all items from session collection 

Session.Clear()Remove all items from session collection  Note: There is no difference between Clear and RemoveAll. RemoveAll() calls Clear(), internally.

Session.Abandon() Cancels the Current Session

Removing Session From Session Variable :Following are the list of methods that are used to removing the session .

Page 14: Session and Cookie Management in .Net

Cookieless Sessions:

•The SessionID() is stored in a non-expiring session cookie in the browser by default. You can specify that session identifiers not be stored in a cookie by setting the cookieless attribute to true in the sessionState section of the Web.config file.

<configuration> <system.web> <sessionState cookieless="true" /> </system.web> </configuration>

•ASP.NET maintains cookieless session state by automatically inserting a unique session ID into the page's URL

http://www.abcdefg.com/s(lit3py55t21z5v55vlm25s55)/orderform.aspx

Page 15: Session and Cookie Management in .Net

ReferenceReference

•http://www.codeproject.com/KB/aspnet/ExploringSession.aspx#2

•http://en.wikipedia.org/wiki/HTTP_cookie

•http://msdn.microsoft.com/en-us/library/ms178582.aspx

Page 16: Session and Cookie Management in .Net

Thank You!Thank You!