lecture7

acceptableseashoreΑσφάλεια

5 Νοε 2013 (πριν από 3 χρόνια και 11 μήνες)

99 εμφανίσεις


ASP.NET


Rina Zviel
-
Girshin

Lecture 7

Rina Zviel
-
Girshin @Paralex

2

Overview


Caching


Web
-
Security

3

ASP.NET Execution Model

Client



Server

public class Hello{

protected void Page_Load(

Object sender, EventArgs e)

{…}

}

Hello.aspx.cs

First request

Postback

Output Cache

Rina Zviel
-
Girshin @Paralex

4

Caching


Caching in general is a temporary storage of state for
faster retrieval.


Caching is a technique widely used in computing to
increase performance

by keeping frequently
accessed or expensive data in memory.


In Web application caching is used to retain pages or
data across HTTP requests and reuse them without
the expense of recreating them.


Cashing web
-
applications occurs

1.
On client (browser caching)

2.
On a server between the client and the web server (proxy caching)

3.
On the web
-
server itself (page caching or data caching).

Rina Zviel
-
Girshin @Paralex

5

ASP.NET Caching


Browser’s and proxy’s caching are not directly
managed by ASP.NET.


However page and data caching can be managed
directly through .aspx pages.


ASP.NET has three kinds of caching that can be
used by Web applications:


output caching

-

caches the dynamic response generated
by a request.


fragment caching

-

caches portions (fragments) of a
response generated by a request.


data caching

-

caches arbitrary objects programmatically.

Rina Zviel
-
Girshin @Paralex

6

Output caching


Output caching

is useful when the contents of the
entire page can be cached.


On a heavily accessed site, caching frequently
accessed pages for even a minute at a time can
result in performance improvement.


While a page is cached by the output cache,
subsequent requests for that page are served from
the output page without executing the code that
created it.

Rina Zviel
-
Girshin @Paralex

7

Output caching


The syntax for output caching:


Add a high
-
level
@OutputCache

directive
-


<%@ OutputCache … %>


When output caching is enabled, an output cache entry
is created on the first
GET

request to the page.


Subsequent requests are served from the output cache
entry until the cached request expires.


an expiration policy that indicates that the page expires in X
minutes from the time it is cached.


<%@ OutputCache Duration="60
"…//60 seconds duration


If another request is received after that time, the page code
is executed and the page can be cached again.


Rina Zviel
-
Girshin @Paralex

8

Example

<%@ OutputCache Duration="60" VaryByParam="none" %>

<script language="C#" runat="server">


void Page_Load(Object sender, EventArgs e)

{


lbl.Text

= DateTime.Now.ToString("G");


}

</script>

<html><body>

<h3>Using the Output Cache</h3>

<p><i>Last generated on:</i><asp:label id=“
lbl
" runat="server"/>

</body> </html>

VaryByParam
=“none”

means
that the page does not vary by
any GET or POST parameters

Values of VaryByParam can be


a parameter, a list of parameters with ;
sign , none and *

Rina Zviel
-
Girshin @Paralex

9

Output


Refreshing of the page does not change the time,
indicating that the second response is being
served from the output cache.

Rina Zviel
-
Girshin @Paralex

10

Fragment caching


Sometimes it is not practical to cache an entire page
-

perhaps portions of the page must be created or
customized for each request.


current stock prices, current time, currency rate,…


It is often worthwhile to identify objects or data that
are expensive to construct and are eligible for
caching


Menu bars, pictures, banner advertisements, static info,…


Once these items are identified, they can be created
once and then cached for some period of time.

Rina Zviel
-
Girshin @Paralex

11

Implementation


To implement a page fragment caching you have to define
user controls.


In addition to the built
-
in server controls you can easily define your
own controls called
user controls
.


Define different areas of your page by creating a separate user
control for each area.


Within each user control define an OutputCache directive to
indicate how this control is cached.


A user control

is almost identical to a normal
.aspx

page with
two differences:


the user control has the
.
ascx

extension rather than .
aspx


The file may not have <html>, <body> or <form> tags.


Rina Zviel
-
Girshin @Paralex

12

usercontol.ascx

<p>


<table bordercolor="red" cellspacing="
0
"
cellpadding="
2
" width="
90
%" border="
1
">


<tbody>


<tr> <td bgcolor="orange" height="
3
"></td> </tr>


</tbody>


</table>

</p>

<p></p>

Rina Zviel
-
Girshin @Paralex

13

Registration of User Controls


User controls are added/included to a Web Forms
page using a
Register

directive:


<%@ Register TagPrefix=“Rina" TagName="Message"
Src=“file.ascx" %>


the
TagPrefix

determines a unique user control’s namespace


the
TagName

is the unique name for the user control


the
Src

attribute is the virtual path to the file containing the user
control.



After registration of the user control on the page you
may add the user control tag to the page


<Rina:Message runat="server"/>


You can use the same user control several times just give
different id’s.

Rina Zviel
-
Girshin @Paralex

14

Example

<%@ Page Language="C#" %>

<%@ Register TagPrefix=“Rina" TagName=“Message"


Src=“usercontol.ascx" %>


<html><head><title>UserControl.aspx</title><body>

Here is some text...

<Rina:Message

id=“
uc
1
" Runat="Server" />

Here is some more text...

<Rina:Message

id=“
uc
2
" Runat="Server" />

Yet some more text...

<Rina:Message

id=“
uc
3
" Runat="Server" />

</body></html>

Rina Zviel
-
Girshin @Paralex

15

Output

Rina Zviel
-
Girshin @Paralex

16

Fragment Caching
Implementation (revisited)


To implement a page fragment caching you have
to define user controls.


Define different areas of your page by creating a
separate user control for each area.


Within each user control define an OutputCache
directive to indicate how this control is cached.


Look at the next example.

Rina Zviel
-
Girshin @Paralex

17

Output

Rina Zviel
-
Girshin @Paralex

18

OurCourse.aspx

<%@ Page Language="C#" %>

<%@ Register TagPrefix="myControls"
TagName="Menu" Src="Menu
1
.ascx" %>


<html><head><title>OurCourse.aspx</title></head>

<body bgcolor="silver">

<myControls:Menu id="UserControl
1
"

Runat="Server">

</myControls:Menu>


<h
1
>Our Course
-
Web
-
Based Systems Development </h
1
>


<hr />


( page generated
: <%=System.DateTime.Now%>
)

</body></html>

Rina Zviel
-
Girshin @Paralex

19

Languages.aspx

<%@ Page Language="C#" %>

<%@ Register TagPrefix="myControls"
TagName="Menu" Src="Menu
1
.ascx" %>


<html><head><title>Languages.aspx</title></head>

<body bgcolor="silver">

<myControls:Menu id="UserControl
1
" Runat="Server">

</myControls:Menu>

<h
1
>Languages
-

We study C# and VB. </h
1
>

<hr />

( page generated:
<%=DateTime.Now%>
)

</body></html>


Rina Zviel
-
Girshin @Paralex

20

Menu
1
.ascx

<%@
Control

Language="c#" %>

<%@ OutputCache Duration="
300
" VaryByParam="menuID" %>

<script runat="server">


string strMenuID;


void Page_Load(Object sender , EventArgs e)


{ strMenuID = Request.Params[ "menuID" ];


if ( strMenuID == null ) strMenuID = "
0
";


} </script>


<table cellpadding="
5
" bgcolor="#eeeeee" border="
2
">


<tbody> <tr> <td> <%

if ( strMenuID == "
0
" )

Response.Write("<b>Our Course</b>");

else response.write("<a href=
\
"ourCourse.aspx?menuID=
0
\
">Our
Course</a>");

Rina Zviel
-
Girshin @Paralex

21

Menu
1
.ascx

Response.Write("</td><td>");


if (
strMenuID == "
1
"

)

Response.Write("<b>Languages</b>");

Else Response.Write("<a href=
\
"Languages.aspx?menuID=
1
\
">
Languages</a>");

Response.Write("</td>");

%>


</tr> </tbody></table>

(menu generated:<%=System.DateTime.Now%> )

Rina Zviel
-
Girshin @Paralex

22

Output

After
refresh

Rina Zviel
-
Girshin @Paralex

23

Data caching


Imagine an application where you display the employees
information.


On one page names, on the other addresses and so on.


The best way to do so is to retrieve the information to a
DataSet and each page will retrieve the information from
the cached DataSet.


ASP.NET provides a full
-
featured cache engine that can be
used by pages to store and retrieve arbitrary objects across
HTTP requests.


You can cache items in memory using the Cache object.


Each ASP.NET application has a single Cache object that remains
valid until application is restarted.


No examples are given.

Rina Zviel
-
Girshin @Paralex

24

Security


Security is one of the primary concerns for
both developers and application architects.


Different types of website have different
security needs:


some sites are the information sites that collect
no information from the user and security
issues are not important


other sites may need to collect sensitive
information from their users (credit card
numbers, bank numbers,..) and need much
stronger security to avoid attacks from the
external entities.

Rina Zviel
-
Girshin @Paralex

25

Security of ASP.NET app


ASP.NET has been built with security in mind.


Security in the context of ASP.NET application
involves three basic operations:


authentication
:

the process of validating the identity of
a user to allow or deny a request


authorization
:

the process of ensuring that users with
valid identity are allowed to access specific resources


impersonation
:

this process enables an application to
ensure the identity of the user and make request to the
other resources. Access to resources will be granted or
denied based on the identity that is being impersonated.

Rina Zviel
-
Girshin @Paralex

26

Authentication


An important part of many Web applications is the
ability to identify users and to control an access to
the resources.


The possibility to recognize the person who tries
to enter the web site or the act of determining the
identity of the requesting entity is known as
authentication
.


The user must present some credentials (usually a
name and a password) in order to be authenticated.

Rina Zviel
-
Girshin @Paralex

27

<
authentication
> element


To activate an ASP.NET authentication service,
you must configure the
<authentication>

element
in the application's configuration file.


This element can have any of the values listed
below


None, Windows, Forms, Passport.


The syntax of authentication in Web.config:

<configuration> <system.web>

<authentication
mode="Forms"
/>

</system.web> </configuration>

Rina Zviel
-
Girshin @Paralex

28

Web.Config


Web.Config

is a part of every ASP.NET application and
provides a nice, central location for storing information that may
be needed in many of your web pages.


The
Web.Config

file contains a minimal amount of information
necessary to enable authentication for application.


To password
-
protect individual directories and its subdirectories add the
web.config file with appropriate authentication mode to the directory.


Example:

<configuration> <system.web>

<authentication>
<deny users=“?”/>

</authentication></system.web> </configuration>


denies (can allow) access to ASP.Net pages contained in the directory to
the anonymous users.

Rina Zviel
-
Girshin @Paralex

29

Remember a ConnectionString?


In ASP.NET there are several options for storing connection
strings.


One of them includes the Web.config file.


In <configuration> tag as a root add a <connectionStrings>
tag with its proper definitions.


<connectionStrings>


<add name="LocalSqlServer" connectionString="data
source=.
\
SQLEXPRESS;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient"/>


</connectionStrings>

Rina Zviel
-
Girshin @Paralex

30

Authentication None


In ASP.NET Web applications, the users
requesting a page are, by default,
anonymous
.


No ASP.NET authentication services are
active.


Note that IIS authentication services can
still be present.

Rina Zviel
-
Girshin @Paralex

31

Authentication Forms


ASP.NET authentication services manage cookies
and redirect unauthenticated users to a logon page.


If an authentication cookie does not exists, the request
is redirected to a logon form.


The user submits his/her credentials to the logon form.


If the user is authenticated a cookie is issued.


The default logon form page name is
Logon.aspx
.


This is often used in conjunction with the IIS
option to allow anonymous access to an
application.

Rina Zviel
-
Girshin @Paralex

32

Form
Authentication
Flow

Rina Zviel
-
Girshin @Paralex

33

Web.config options

<configuration>

<system.web>

<authentication
mode="Forms"
>


<forms
name=".ASPXCOOKIEDEMO"
loginUrl="Login.aspx"
protection="all"


timeout="
30
"

path="/">


<!
--
protection="[All| None|
Encryption|Validation]"
--
>


</forms>

</authentication>

</system.web>

</configuration>



The authentication section can contain
an optional
forms

element and its
attributes


name



the name of the browser
authentication cookie (the default value
.ASPXAYTH)


loginURL



the name of the auth. page
the user is redirected to (the default
value login.aspx)


timeout



amount of time before cookie
expires in min (the default
30
min)


protection


the way cookie data is
protected (the default All) using DES or
tripleDES encryption


path


the path used for the cookie (the
default /)

Rina Zviel
-
Girshin @Paralex

34

Encryption


The .NET framework includes cryptographic functions for
encryption, digital signatures, hashing and random number
generation.


Supported algorithms include:


asymmetric encryption
-

RSA and DSA


symmetric encryption
-

DES, TripleDES, RC
2


hashes
-

MD
5
, SHA
1
.


The implementation uses a stream
-
based model.


For example:


A stream of data from a file can be routed into an encryption object
and the resulting stream sent to the network.


<user name=“Rina"
password="GASDFSA
9823598
ASDBAD"/>

Rina Zviel
-
Girshin @Paralex

35

Output

After the incorrect
credentials are
submitted

After the correct
credentials and
default.aspx page
exists

Rina Zviel
-
Girshin @Paralex

36

Example

<%@ Page Language="C#" %>

<script runat="server">


void Button_Click(Object sender , EventArgs e)


{


if ( IsValid )


{


if (Username.Text == "rina" && Password.Text == "password")


FormsAuthentication.RedirectFromLoginPage(
Username
.Text,
chkbox
.Checked );


else
lbl
.Text = "Bad username/password!";


}


}

</script>

Rina Zviel
-
Girshin @Paralex

37

Example

<html><head> <title>Login.aspx</title></head>

<body> <form runat="Server"> <h
2
>Please Login:</h
2
>

<asp:Label id="
lbl
" Runat="Server"></asp:Label>

<p> <b>Username:</b> <br /> <asp:TextBox id="
Username
"
Runat="Server"></asp:TextBox> <asp:RequiredFieldValidator id=“val
1
"
Runat="Server" Text="Required!"
ControlToValidate="Username"></asp:RequiredFieldValidator></p>


<p><b>Password:</b> <br /> <asp:TextBox id="
Password
"
Runat="Server"></asp:TextBox> <asp:RequiredFieldValidator id=“val
2
"
Runat="Server" Text="Required!"
ControlToValidate="Password"></asp:RequiredFieldValidator></p>


<p> <asp:CheckBox id=“
chkbox
" Runat="Server"></asp:CheckBox>

Remember me with a cookie? </p> <p>

<asp:Button id="
Button
1
" onclick="Button_Click" Runat="Server"
Text="Login!"></asp:Button></p>

</form></body></html>

Rina Zviel
-
Girshin @Paralex

38

Output

After the correct
credentials and
default.aspx page
exists

Rina Zviel
-
Girshin @Paralex

39

Explanation


RedirectFromLoginPage(user,cookiestate)

method
is called if the correct name/password are submitted.


It remembers a username and a Boolean value
indicating if a persistent cookie should be created.


It creates a cookie on the user’s browser that contains an
Authentication Ticket.


Automatically redirects all authorized users to the
page the original request was sent from (in our case
default.aspx).


If Login.aspx was a direct link then it can give an
unexisting page or a Default.aspx page.

Rina Zviel
-
Girshin @Paralex

40

Authorization


Once an authenticated identity is available, it must be determined
whether that identity (usually user) can access a given resource
by validation of the credentials.


This process is known as
authorization
.


ASP.NET works in conjunction with IIS to provide
authentication and authorization services to applications:


ASP.NET also supports
Microsoft Passport authentication

and
provides a convenient implementation of Forms
-
based (Cookie)
authentication.


The Passport SDK must be installed on the machine.


The current subscription fee for the service is
10.000
$ per year.


For details: www.passport.com/business


The designer needs to know how the security works and choose
the appropriate security model for different applications.

Rina Zviel
-
Girshin @Paralex

41

Configuring forms authorization


Permissible elements for authorization directives are either
allow

or
deny
.


Each allow or deny element must contain a
users

or a
roles

attribute.


There are
2
special user names:


*
: All users


?
: Anonymous (unauthenticated) users


Examples:

<authorization>

<allow users=“Rina" />

<deny users="*" />

</authorization>

<authorization>


<allow users=“Rina@idc.ac.il” />


<allow roles="Admins" />


<deny users="*" />

</authorization>

Only Rina has
an access to the
resource

Rina@idc.ac.il has an
Admins role and access

Rina Zviel
-
Girshin @Paralex

42

Sign out


If you want to create a page that returns a current user to
anonymity you should use the
SignOut

method of
FormsAuthentication class.


Calling this method removes either a session or a cookie
regardless of whether the cookie is temporary or permanent.


Can be useful in web
-
mail.

<%@ Page Language="C#" %>

<script language="C#" runat=server>

void Page_Load(Object sender , EventArgs e)

{
FormsAuthentication.SignOut();
}

</script>

<html><head><title>SignOut.aspx</title></head>

<body><h
2
>Goodbye!</h
2
></body></html>

Rina Zviel
-
Girshin @Paralex

43

Authentication Windows


This type of authentication is possibly the easiest of all to
implement.


The
Windows authentication

provider is the
default

provider
for ASP.NET.


It authenticates users
based on

the users' Windows accounts.


Windows authentication in ASP.NET actually relies on IIS to
do the authentication.


IIS has already authenticated their Windows credentials
-

IIS is
performing the verification of the credentials.


IIS can be configured so that only users on a Windows domain
can log in.


There is no need to write any code to validate the user.

Rina Zviel
-
Girshin @Paralex

44

Using Windows Authentication


Windows
Authentication
’s dialog box asking
user to enter a username and a password:

Rina Zviel
-
Girshin @Paralex

45

Authentication Flow


If a user attempts to access a page and is not authenticated
then he/she will be send to a dialog box asking them to
enter their username and password.


This information is then passed to the Web server.


The Web server checks this info against the list of users in
the domain.



If the user has supplied valid credentials then an access to
the page/site is granted.


The identity of the user is then passed to the ASP.NET
engine.

Rina Zviel
-
Girshin @Paralex

46

Resources access


Later when a user requests specific resources, this
request goes to IIS.


IIS authenticates the user and attaches the security
token to it and then passes the authenticated request
and security token to ASP.NET.


If impersonation is enabled, ASP.NET impersonates the
user using the security token attached and sees whether the
user is authorized to access the resources in the
<authorization> section in Web.config file.


If the access is granted ASP.NET will send the
requested resources through IIS.


If not it sends error message to the user.

Rina Zviel
-
Girshin @Paralex

47

Authentication Windows


Windows authentication can be used in conjunction
with almost all authentication methods provided by
IIS:


Anonymous
-

no logon is required and anyone is allowed to gain access
to data. The browser does not send any credentials or user info with this type
of request.


Basic


compatible with all browsers,firewalls,proxies
-

username and
password are transmitted as
a plain text



Digest


compatible with Internet Explorer, all firewalls and proxies
-

username and password are not transmitted as a plain text but
as encoded
hash


Integrated Windows


compatible with Internet Explorer and
not all

firewalls and proxies
-

username and password are not transmitted as a plain
text but
uses either NTLM or Kerberos protocols for user identification.

Rina Zviel
-
Girshin @Paralex

48

Any Questions?