Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

Networking & Security Implementation in ASP.

NET

Objective
Implementing state Management in ASP.NET Sending E-Mail form an ASP.NET Page Securing ASP.NET application

State Management
We are working in a connectionless environment Which means we cant use normal variables to persist data between server round trips, and pages. Instead we have a range of techniques provided by Asp.Net and HTTP that we can use:

State Management
Between Server Round Trips
ViewState Hidden form fields Querystrings

Between Pages
Querystrings Server.Transfer Cookies
HTML Forms

In A Session
Session Variables Cookies Cookies (with expiry) Database or other storage Application Variable Cache Object appSettings in Web.Config

Between Sessions

Application

ViewState
ASP.Net mechanism to persist data through server round trips on a single page. All ASP controls (including the Page object) have EnableViewState property that is defaulted to true You can add your own data to view state using : [c#] ViewState.Add("MyVariable,MyValue); vb] ViewState.Add(MyVariable,MyValue) ViewState materializes as a hidden field in the HTML output, with all the ViewState values encoded to ensure they come from the page that created them.

Querystrings
Querystring can pass data from one page to another, even across web sites and servers. Can by simple a URL in a hyperlink:
<A href="anotherpage.aspx?MyVariable=MyValue&MyOtherV ariable=MyOtherValue">Click me</a>

QueryStrings

Or you could use a redirect in code: [c#]


Response.Redirect(" anotherpage.aspx?MyVariable=MyValue&MyOtherVariabl e=MyOtherValue"); [vb] Response.Redirect(" anotherpage.aspx?MyVariable=MyValue&MyOtherVariabl e=MyOtherValue");

QueryStrings
Read querystring values through Request.QueryString [c#] MyValue = Request.QueryString["MyVariable"]; [vb] MyValue = Request.QueryString("MyVariable)

Server.Transfer and Context.Items

Use to pass a variable from one to another without changing the Page URL. In the first page, and the values you want to the Content.Items collection:
[c#] Context.Items.Add("MyVariable,MyValue);

Then transfer to the second page: [c#] Server.Transfer("SecondPage.aspx");

Server.Transfer and Context.Items

On the second page retrieve the value from the Context.Items collection and cast to the type you need:
[c#] MyValue = (MyType)Context.Items["MyVariable"]; [vb] MyValue = Ctype(Context.Items("MyVariable),MyType)

Cookies
Cookies store data in the browser
Either memory resident only (because no Expiry Date is given) and so only available throughout a session. Or if an Expiry Date is given then Cookies will persist between sessions for a user (with a consistent profile, login or machine)
[c#] HttpCookie ck = new HttpCookie("MyVariable",MyValue); [vb] Dim ck as new HttpCookie("MyVariable",MyValue)

Cookies
Create a cookie using HttpCookie and then add it to Response.Cookies collection to send it to the browser.
[c#] ck.Expires = DateTime.Now.AddDays(30); Response.Cookies.Add(ck); [vb] ck.Expires = DateTime.Now.AddDays(30) Response.Cookies.Add(ck)

Cookies
Read a cookie by retrieving it from the Request.Cookies collection: [c#] HttpCookie ck; ck = Request.Cookies["MyVariable"]; [vb] Dim ck as HttpCookie ck = Request.Cookies("MyVariable)

Cookies
Delete a cookie by setting it's expiry date to yesterday (or earlier) and adding to the Response.Cookies collection

[c#] ck.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(ck);


[vb] ck.Expires = DateTime.Now.AddDays(-1) Response.Cookies.Add(ck)

Session State

Session state is maintained on a per-client basis. When a client first accesses any page in an application, an ASP.NET generated session ID is created. Session state is used for things like:
Shopping carts, Viewing preferences, other

Session state is the most flexible and, in general, the most efficient means of maintaining client-specific state.

Session Events

Event Session_OnStart

Description Occurs when a new user accesses a page thats part of the application. Can be used to initialize: session variables, session level objects, and begin database connections.

Session_OnEnd

Happens when a session times out. Can be used to any final cleanup and to close a database connection.

Using the Session Object


Session state is maintained on behalf of each client within an ASP.NET application. When a new client begins to interact with the application, a new session ID (or session key) is generated The ID is associated with all subsequent requests from that same client. The state is retained in memory on the server in the default session state configuration. By default, the session key is retained on the client side in a cookie. (there is an alternative in cases where cookies do not work)

Application State
Application state is where information that is global to the application may be stored. For efficiency, this state is typically stored once and then read from many times. Often used for application statistics variables or constant global data:
Number of users who have accessed site Counts of different types of browsers Can prefetch static data from a database or file

Should be used with care

Application Events
Event Application_OnStart Description Happens once when the first user access the app. Can be used to retrieve or initialize information that will be used across all sessions.

Application_OnEnd

Happens once when the last user leaves the app. Can be used to clean up any app-level variables and objects.

Application_OnBeginRequest

Happens every time a page in the application is requested, before the request is serviced.

Application_OnEndRequest

Happens after each request is serviced. The last event that can have

an effect on the response.

Using the Application Object


Application object is implicitly locked for you when data is read from or written to it. May make more sense to avoid using application object and use data cache if you are just storing global constants. Application object must be used if you are using shared, updatable data.

Sending E-Mail
ASP.NET pages can be configured to send email through the server's SMTP (Simple Mail Transfer Protocol) service The SMTP service is included as a component of Microsoft Windows Server and XP Professional Web pages that produce automated email messages must import the System.Net.Mail namespace This namespace contains classes used to send electronic mail to an SMTP server for delivery. <%@ Import Namespace="System.Net.Mail" %>

System.Net.Mail
Three classes are included in the namespace. The MailMessage class represents the content of a mail message The SmtpClient class transmits email to the SMTP host server designated for mail delivery. Email attachments are sent using the Attachment class.

SmtpClient Class
All email messages are sent through an SmtpClient object
SmtpClient EmailClient = New SmtpClient(host) The SmtpClient object supplies the Send() method through which email messages are sent through the host server.
EmailClient.Send(from, to, subject, body) In this format, from is the "From" address, to is the "To" address, subject is the "Subject" line, and body is the "Body" of the message. All four parameters must be present and must appear in the order given.

The MailMessage Class


to define message components, is through a MailMessage object . This object defines the sender, recipients, subject, and message body required by the SmtpClient, which then sends the final MailMessage
MailMessage MailMessage = new MailMessage ();

Message Attachments
An Attachment object is created giving the path to the file to be attached to the message Attachment object is added to the MailMessage's Attachments collection Path to the attachment file is its physical path on the server The Server.MapPath() method to convert a relative path to a physical path.

Authentication

Authentication is the process of obtaining identification credentials from a user validating those credentials against some authority. ASP.NET implements authentication through authentication providers

Types of Authentication Providers

Windows Authentication Form Authentication Passport Authentication

Windows Authentication Provider

It relies on IIS to provide authenticated users If you use IIS authentication, the provider module uses the authenticated identity passed in from IIS IIS authenticates the identity using basic, digest, or Windows authentication ASP.NET attaches a WindowsPrincipal object to the current request.

Form Based Authentication

Forms authentication generally refers to a system in which unauthenticated requests are redirected to an HTML form, using HTTP client-side redirection Forms authentication is a good choice if your application needs to collect its own user credentials at logon time through HTML forms.

Form Based Authentication

Valid user/password pairs can be placed in the <credentials> section of a configuration file. <credentials passwordFormat = "SHA1" > <user name = "Mary" password = pass" /> <user name = "John" password = pass1" /> </credentials>

Password Format
Value
Clear

Description
Passwords are stored in clear text. The user password is compared directly to this value without further transformation

MD5

Passwords are stored using a Message Digest 5 ( MD5 ) hash digest. When
credentials are validated, the user password is hashed using the MD5 algorithm and compared for equality with this value. The clear-text password is never stored or compared when using this value. This algorithm produces better performance than SHA1.

SHA1

Passwords are stored using the SHA1 hash digest. When credentials are
validated, the user password is hashed using the SHA1 algorithm and compared for equality with this value. The clear-text password is never stored or compared when using this value. Use this algorithm for best security.

Authorization Authorization determines whether an identity should be granted the requested type of access to a given resource. ASP.NET implements authorization through authorization providers

Authorization Provider
ASP.NET Authentication Provider File authorization
File authorization is performed by the FileAuthorizationModule, and is active when the application is configured to use Windows authentication. It checks the access control list ( ACL ) of the file to determine whether a user should have access to the file. ACL permissions are verified for the Windows identity or, if impersonation is enabled

Description

URLAuthorization

URL authorization is performed by the URLAuthorizationModule, which maps users and roles to URLs in ASP.NET applications. This module can be used to selectively allow or deny access to arbitrary parts of an application ( typically directories ) for specific users or roles.

Authorization

The general syntax for the authorization section is as follows: <authorization> < [ allow | deny ] [ users ] [ roles ] [ verbs ] /> </authorization> The allow or deny element is required, and either the users or the roles attribute must be specified. Both can be included, but both are not required. The verbs attribute is optional. The allow and deny elements grant and revoke access, respectively. Each element supports three attributes, which are defined in the following table

Authorization
Identity * ? Description Refers to all identities Refers to the anonymous identity

Authorization
<authorization> <allow users = "Mary" /> <allow roles = "Admins" /> <deny users = "John" /> <deny users = "?" /> </authorization>

Impersonation

impersonation refers to a process in which a COM object executes with the identity of the entity on behalf of which it is performing work If impersonation is enabled for a given application, ASP.NET always impersonates the access token that IIS provides The impersonation occurs regardless of the type of authentication being used in the application and whether the user is authenticated, Impersonation is disabled at the computer level by

Impersonation

To enable Impersonation <identity impersonate = "true" name = "username" password = "password" />

You might also like