Вы находитесь на странице: 1из 12

144 members have rated this article.

Result:
Popularity: 10.24. Rating: 4.74 out of 5.

Introduction

Forms Authentication in ASP.NET can be a powerful feature. With very little code and
effort, you can have a simple authentication system that is platform-agnostic. If your
needs are more complex, however, and require more efficient controls over assets,
you need the flexibility of groups. Windows Authentication gives you this flexibility,
but it is not compatible with anything but Internet Explorer since it uses NTLM,
Microsoft's proprietary authentication system. Now you must choose how to manage
your assets: provide multiple login pages / areas and force users to register for each,
or assign groups to users and limit access to pages / areas to particular groups.
Obviously, you must choose the latter.
Role-based security in Forms Authentication is one thing Microsoft left out in this
round for .NET, but they didn't leave you high-and-dry. The mechanisms are there,
they're just not intuitive to code. This tutorial will cover the basics of Forms
Authentication, how to adapt it to make use of role-based security, and how to
implement role-based security on your site with single sign-ons.

Prerequisites

This tutorial is all about role-based security with Forms Authentication, a detail that
Microsoft left out of .NET for this round. This tutorial will use different techniques that
are almost completely incompatible with the standard Forms Authentication, save the
setup, which we'll cover shortly.
To follow along in this tutorial, you'll need to create a database, a web application,
several secured directories, and a few ASP.NET Web Forms (pages).

Creating the Database

We will create a simple database containing a flat table for this tutorial. Using the
<credentials/> section of the Web.config file is not an option because no
mechanism for roles is supported. For the purposes of brevity, the table we create
will be very simple. You're welcome to expand the database to make use of relations
(what I would do and actual do use on several sites) for roles. The implementation
does start to get a little messy depending on how you do it, and the details are left
up to you. This is merely a tutorial about developing role-based security.
So, choose what database management system you want to use (DBMS). For this
tutorial, we'll choose the Microsoft Data Engine (MSDE) available with Visual Studio
.NET, Office XP Developer, and several other products. We'll add one database, say
web, and then add one table, say users. To the users table, we'll add three fields:
username, password, and roles. Set the username field to the primary key (since it'll
be used for look-ups and needs to be unique), and optionally create an index on the
username and password fields together. If you're using Table-creation SQL Scripts,
your script might look something like this:
CREATE
DATABASE web

CREATE TABLE users


(
username nvarchar(64) CONSTRAINT users_PK PRIMARY KEY,
password nvarchar(128),
roles nvarchar(64)
)

CREATE INDEX credentials ON users


(
username,
password
)
Feel free to add some credentials to your database, picking a few roles you think are
good group names for your site, such as "Administrator", "Manager", and "User". For
this tutorial, put them in comma-delimited format in the "roles" field like the
following, pipe-delimited (|) table:
username|password|roles
"hstewart"|"codeproject"|"Administrator,User"
"joe"|"schmoe"|"User"
Take note to make the roles case-sensitive. Now let's move on to creating our pages
necessary for role-based Forms Authentication.

Creating the Login Pages

If you haven't already done so, create a new Web Application, or attach to an existing
Web Application, such as your web server's document root, "/". For this tutorial, we'll
assume the Web Application resides in "/", though the procedure for any Web
Application is the same.
Before we create any pages or setup our Web.config file, you must understand one
thing: the login.aspx (or whatever you call your login page) must be public. If it
isn't, your users will not be able to log-in, and could be stuck in an infinite loop of
redirects, though I've not tested this and don't care to. So, this tutorial will assume
that login.aspx is in "/", while we have two secured sub-directories, users and
administrators.
First, we must create a Forms Authentication login system that supports roles.
Because Microsoft did not provide for this easily, we will have to take over the
process of creating the authentication ticket ourselves! Don't worry, it's not as hard
as it sounds. A few pieces of information are needed, and the cookie has to be stored
under the right name - the name matching the configured name for Forms
Authentication in your root Web.config file. If these names don't match, ASP.NET
won't find the Authentication Ticket for the Web Application and will force a redirect
to the login page. For simplicity, we will put the code directly into the ASP.NET Web
Form, which is easier to code for DevHood and should look something like the
following:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<head>
<title>Login</title>
</head>
<script runat="server">
// If you're using code-behind, make sure you change "private" to
// "protected" since the .aspx page inherits from the .aspx.cs
// file's class
private void btnLogin_Click(Object sender, EventArgs e)
{
// Initialize FormsAuthentication, for what it's worth
FormsAuthentication.Initialize();

// Create our connection and command objects


SqlConnection conn =
new SqlConnection("Data Source=localhost;Initial Catalog=web;");
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT roles FROM web WHERE username=@username " +
"AND password=@password";

// Fill our parameters


cmd.Parameters.Add("@username", SqlDbType.NVarChar, 64).Value =
Username.Value;
cmd.Parameters.Add("@password", SqlDbType.NVarChar, 128).Value =
FormsAuthentication.HashPasswordForStoringInConfigFile(
Password.Value, "md5"); // Or "sha1"

// Execute the command


conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
// Create a new ticket used for authentication
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Ticket version
Username.Value, // Username associated with ticket
DateTime.Now, // Date/time issued
DateTime.Now.AddMinutes(30), // Date/time to expire
true, // "true" for a persistent user cookie
reader.GetString(0), // User-data, in this case the roles
FormsAuthentication.FormsCookiePath);// Path cookie valid for

// Encrypt the cookie using the machine key for secure transport
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of auth cookie
hash); // Hashed ticket

// Set the cookie's expiration time to the tickets expiration time


if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;

// Add the cookie to the list for outgoing response


Response.Cookies.Add(cookie);

// Redirect to requested URL, or homepage if no previous page


// requested
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null) returnUrl = "/";

// Don't call FormsAuthentication.RedirectFromLoginPage since it


// could
// replace the authentication ticket (cookie) we just added
Response.Redirect(returnUrl);
}
else
{
// Never tell the user if just the username is password is incorrect.
// That just gives them a place to start, once they've found one or
// the other is correct!
ErrorLabel = "Username / password incorrect. Please try again.";
ErrorLabel.Visible = true;
}

reader.Close();
conn.Close();
}
</script>
<body>
<p>Username: <input id="Username" runat="server"
type="text"/><br />
Password: <input id="Password" runat="server" type="password"/><br
/>
<asp:Button id="btnLogin" runat="server" OnClick="btnLogin_Click"
Text="Login"/>
<asp:Label id="ErrorLabel" runat="Server" ForeColor="Red"
Visible="false"/></p>
</body>
</html>
You'll notice above that we do one other thing with our passwords: we hash them.
Hashing is a one-way algorithm that makes a unique array of characters. Even
changing one letter from upper-case to lower-case in your password would generate
a completely different hash. We'll store the passwords in the database as hashes,
too, since this is safer. In a production environment, you'd also want to consider
having a question and response challenge that a user could use to reset the
password. Since a hash is one-way, you won't be able to retrieve the password. If a
site is able to give your old password to you, I'd consider steering clear of them
unless you were prompted for a client SSL certificate along the way for encrypting
your passphrase and decrypting it for later use, though it should still be hashed.
Note: without using HTTP over SSL (HTTPS), your password will still be sent in plain-
text across the network. Hashing the password on the server only keeps the stored
password secured. For information about SSL and acquiring a site or domain
certificate, see http://www.versign.com or http://www.thawte.com.
If you don't want to store hashed passwords in the database, change the line that
reads
FormsAuthentication.HAshPasswordForStoringInConfigFile(Password.Value,
"md5") to just Password.Value.
Next, we'll need to modify the Global.asax file. If your Web Application doesn't have
one already, right-click on the Web Application, select "Add->Add New Item...-
>Global Application Class". In either the Global.asax or Global.asax.cs (or
Global.asax.vb, if you're using VB.NET), find the event handler called
Application_AuthenticateRequest. Make sure it imports / uses the
System.Security.Principal namespace and modify it like so:
protected void Application_AuthenticateRequest(Object sender,
EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id =
(FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;

// Get the stored user-data, in this case, our roles


string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
}
}
}
What's happening above is that since our principal (credentials - which are your
username and roles) is not stored plainly as part of our cookie (nor should it, since a
user could modify their list of role-memberships), it needs to be generated for each
request. The FormsAuthenticationTicket is actually encrypted as part of a cookie
using your machine key (usually configured in machine.config) and the
FormsAuthentication module decrypts the tick as part of the user's identity. If you
search long and hard enough on Microsoft MSDN web site, you'll find this
documentation buried. We use the UserData to obtain the list of roles and generate a
new principal. Once the principal is created, we add it to the current context for the
user, which the receiving page can use to retrieve credentials and role-memberships.

Securing Directories with Role-based Forms Authentication

To make the role-based authentication work for Forms Authentication, make sure you
have a Web.config file in your Web Application root. For the authentication setup, this
particular Web.config file must be in your Web Application's document root. You can
override the <authorization/> in Web.config files for sub-directories.
To begin, make sure your Web.config file has at least the following:
<configuration>
<system.web>
<authentication mode="Forms">
<forms name="MYWEBAPP.ASPXAUTH"
loginUrl="login.aspx"
protection="All"
path="/"/>
</authentication>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</configuration>
The FormsAuthentication name (MYWEBAPP.ASPXAUTH) above it arbitrary, although the
name there and the name in the HttpCookie we created to hold the hashed
FormsAuthenticationTicket must match, for even though we are overriding the
ticket creation, ASP.NET still handles the authorization automatically from the
Web.config file.
To control authorization (access by a particular user or group), we can either 1) add
some more elements to the Web.config file from above, or 2) create a separate
Web.config file in the directory to be secure. While, I prefer the second, I will show
the first method:
<configuration>
<system.web>
<authentication mode="Forms">
<forms name="MYWEBAPP.ASPXAUTH"
loginUrl="login.aspx"
protection="All"
path="/"/>
</authentication>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
<location path="administrators">
<system.web>
<authorization>
<!-- Order and case are important below -->
<allow roles="Administrator"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
<location path="users">
<system.web>
<authorization>
<!-- Order and case are important below -->
<allow roles="User"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
</configuration>
The Web Application always creates relative paths from the paths entered here (even
for login.aspx), using it's root directory as the starting point. To avoid confusion with
that condition and to make directories more modular (being able to move them
around without changing a bunch of files), I choose to put a separate Web.config file
in each secure sub-directory, which is simply the <authorization/> section like so:
<configuration>
<system.web>
<authorization>
<!-- Order and case are important below -->
<allow roles="Administrator"/>
<deny users="*"/>
</authorization>
</system.web>
</configuration>
Notice, too, that the role(s) is/are case-sensitive. If you want to allow or deny access
to more than one role, delimit them by commas.
That's it! Your site is setup for role-based security. If you use code-behind, compile
your application first. Then try to access a secure directory, such as /administrators,
and you'll get redirected to the login page. If login was successful, you're in, unless
your role prohibits it, such as the /administrators area. This is hard for the login.aspx
page to determine, so I'd recommend a Session variable to store the login attempts
and after so many times, return an explicit "Denied" statement. There is another
way, however, which is discussed below.

Conditionally Showing Controls with Role-based Forms


Authentication

Sometimes it's better to show / hide content based on roles when you don't want to
duplicate a bunch of pages for various roles (user groups). Such examples would be
a portal site, where free- and membership-based accounts exist and membership-
based accounts can access premium content. Another example would be a news page
that would display an "Add" button for adding news links if the current user is in the
"Administrator" role. This section describes how write for such scenarios.
The IPrincipal interface, which the GenericPrincipal class we used above
implements, has a method called IsInRole(), which takes a string designating the
role to check for. So, if we only want to display content if the currently logged-on
user is in the "Administrator" role, our page would look something like this:
<html>
<head>
<title>Welcome</title>
<script runat="server">
protected void Page_Load(Object sender, EventArgs e)
{
if (User.IsInRole("Administrator"))
AdminLink.Visible = true;
}
</script>
</head>
<body>
<h2>Welcome</h2>
<p>Welcome, anonymous user, to our web site.</p>
<asp:HyperLink id="AdminLink" runat="server"
Text="Administrators, click here." NavigateUrl="administrators/"/>
</body>
</html>
Now the link to the Administrators area of the web site will only show up if the
current user is logged in and is in the "Administrator" role. If this is a public page,
you should provide a link to the login page, optionally setting the QueryString
variable called ReturnUrl to the path on the server you want the user to return to
upon successful authentication.
Table of Contents:

• What is Microsoft .NET?


• What are the benefits of Microsoft .NET for measurement and automation?
• What is eXtensible Markup Language (XML)?
• What is Simple Object Access Protocol (SOAP)?
• What are the main components of Microsoft .NET?
• What are Experiences?
• What are Clients?
• What are Services?
• What are Servers?
• What are Tools?

What is Microsoft .NET?

Microsoft recently announced the .NET platform as their latest vision for building, deploying, and
running distributed applications and systems across the Internet. The .NET platform takes
advantage of several new technology standards, such as eXtended Markup Language (XML) and
Simple Object Access Protocol (SOAP), to fully utilize the abundance of computing and
communications resources available and in use today. With the .NET platform, Microsoft hopes to
supply the next-generation user experience by providing users with more personalization and
seamless integration between multiple applications and devices.
What are the benefits of Microsoft .NET for measurement and automation?

Microsoft’s goals for the .NET platform fit well into the National Instruments vision for networked
measurement and automation and will thus greatly benefit the measurement and automation
industry. National Instruments provides measurement and automation products that harness the
power and availability of computers and the Internet so you can integrate networked
measurements into your applications. Many of our products already contain features for
integrating networked measurements, and we are committed to providing even more of these
features in the future. Through this vision, you can expand NI-based measurement and
automation applications beyond a single computer by seamlessly extending the acquisition,
analysis, and presentation of data over a local network or the Internet to create distributed virtual
instruments. By distributing your virtual instruments, you can publish measurement data over the
Internet, take remote measurements, and distribute execution of a program.
National Instruments is closely evaluating many of the promised capabilities of the
.NET platform so that we can help you improve your applications by utilizing some of
these technologies.
What is eXtensible Markup Language (XML)?

The next-generation Internet will take advantage of a new data language technology called
eXtensible Markup Language (XML). XML is an increasingly popular standard that has been
developed through the open Internet standards groups (www.w3c.org) to provide the ability to
present data and information and describe the nature of data. XML allows the same information to
be consumed by multiple applications or configured appropriately within a Web browser or other
display. National Instruments currently offers several products that have integrated XML features.
With our test management software, National Instruments TestStand, you can generate XML-
based test reports, which provide great flexibility for displaying test data in a variety of formats.
For National Instruments LabVIEW and LabWindows/CVI, NI also offers an add-on Database
Connectivity toolset that provides XML capabilities.
What is Simple Object Access Protocol (SOAP)?
Simple Object Access Protocol (SOAP) is a lightweight protocol for exchanging information in a
decentralized, distributed environment. Specifically, SOAP is an XML-based protocol that consists
of three parts:
· An envelope that defines a framework for describing what is in a message and how to process it
· A set of encoding rules for expressing instances of application-defined data types
· A convention for representing remote procedure calls and responses
What are the main components of Microsoft .NET?

Microsoft .NET provides the framework for the next generation of Internet-based applications.
Because some of the Microsoft .NET features might be applicable to measurement and
automation applications, it is important to take a closer look at the components of Microsoft
.NET– Experiences, Clients, Services, Servers, and Tools–to better understand the new
framework.
What are Experiences?

The Experiences component of Microsoft .NET aims to provide a more productive and purposeful
experience by using XML to better organize and display data, as well as integrating digital media
support and privacy-enabling technologies for management and control of personal information.
In the future, new dynamic delivery systems for secure and seamless installation, updates,
roaming, and offline operation will be a large part of the .NET experience. Microsoft also will offer
a selection of .NET experiences including Windows .NET, MSN .NET, Office .NET, bCentral .NET,
and Visual Studio .NET.
Similar to Microsoft’s goal of providing seamless user experiences within the .NET
platform, National Instruments strives to integrate the most user friendly and
productive experiences into our Web site–ni.com–our hardware resource manager–NI
Measurement and Automation Explorer (MAX). We also integrate these experiences
into our text-based language tools that make up Measurement Studio as well as our
application development environments–LabVIEW, LabWindows/CVI, and TestStand.
What are Clients?

Microsoft .NET Clients are “smart” devices including PCs, laptops, workstations, phones,
handheld computers, Tablet PCs, game consoles, and other devices. Such .NET clients are
unique because they use software that is created to enable them to operate in the .NET platform.
Specifically, these smart devices allow access to your information in an appropriate form anytime
and from anywhere. .NET clients consume XML Web services and provide .NET experiences by
optimizing the way information is presented and gathered–from converting text to speech to
recognizing handwriting, regardless of the location, type, and number of clients you use. Some of
the .NET client software Microsoft will offer include Windows CE, Windows Embedded, Windows
2000, and Windows XP.
National Instruments offers you a variety of tools for use in your distributed
measurement and automation systems, including LabVIEW or Measurement Studio to
create browser-based applications, NI-DAQ to perform remote device access (RDA),
DataSocket technology to distribute and present data over the Web, LabVIEW Real-
Time for embedded deterministic applications, and FieldPoint for networked,
distributed I/O. Hardware clients also are available using our PXI product line, which
includes embedded controllers that you can use with the software mentioned above.
What are Services?

The .NET Services component is crucial to driving the success of the new Microsoft vision. A
.NET service is a code module that can be distributed and accessed across the Internet from any
platform or operating system. At the core, .NET services are software modules built for data
exchange to help applications, services, and devices work together. The .NET services extend
modular and component-based application development to Internet-enabled applications. The
.NET services also attempt to address the integration issues of dispersed devices and
applications. Because these services transfer data using the increasingly popular XML standard,
they are commonly referred to as XML Web Services. You will see many general-purpose .NET
services appearing over the course of the next few years. Microsoft is developing a variety of
these services and also is working with other companies to create .NET services. Microsoft
currently has a .NET service, called Passport, available. With Passport, developers can
outsource user authentication. Microsoft is developing a user-centric set of 12 core XML Web
services, codenamed HailStorm, for release in 2002.
National Instruments currently offers a variety of services available through our Web
site, ni.com. These services include the Instrument Driver Network, which provides
convenient access to instrument drivers. To help you determine which hardware is
best suited for your application, our services include various advisors such as the
Camera Advisor, DAQ Advisor, and Upgrade Advisor. In the future, NI looks forward
to expanding our current Web-based services to .NET Web services that can be
accessed automatically by our application development language tools, such as
LabVIEW, LabWindows/CVI, Measurement Studio, and TestStand.
What are Servers?

The Microsoft .NET Enterprise Servers, including the Microsoft Windows 2000 server family,
make up the Microsoft .NET server infrastructure for deploying, managing, and orchestrating XML
Web services. Some of the existing Microsoft servers, such as SQL Server 2000 and Exchange
Server 2000, have been extended to take advantage of the new .NET Framework. Microsoft also
is creating several new enterprise server lines that take advantage of the .NET platform. The
servers of interest to the measurement and automation industry include the Mobile Information
2001 Server for providing information to mobile devices, the BizTalk Server 2000 for integrating
applications with corporate business applications, and the Internet Security and Acceleration
Server 2000 for maintaining the privacy required when taking advantage of these new
technologies.
What are Tools?

To take advantage of .NET capabilities, Microsoft introduces the Visual Studio .NET application
development environment. Visual Studio .NET is Microsoft’s next generation development tool,
built especially for developing and deploying applications that take advantage of the .NET
Framework. Visual Studio .NET helps developers build XML Web services and applications using
the language of their choice. Visual Studio .NET provides a choice of open, extensible,
development languages. These languages include the following features:
· Object-oriented programming features in Visual Basic .NET
· Additional Visual C++ features that enable you to build .NET applications
· New Visual C# language (pronounced “C-Sharp”), which combines rapid application
development (RAD) with C and C++

Yo u a r e h e r e : N I H o m e > N I D e ve l o p e r Z o n e > D e ve l o p m e n t L i b r a r y >


Measurement and Automation Software > Measurement Studio >
Vi s u a l S t u d i o . N E T
10 ratings: Frequently
4.20 out of 5 Rate this Document

Asked Questions about Microsoft


.NET - Part 2 of 3
Print this Page

Part 2 of 3 of answers to some of the most commonly asked questions about


Microsoft .NET, National Instruments, and the the affect of .NET on
measurement and automation industry.
Table of Contents:

• What is the .NET Framework?


• What is the Common Language Runtime (CLR)?
• What are the changes to the Visual Basic programming language?
• What is Visual C#?
• What are the changes in Visual C++?
• Are .NET Tools only for building Web applications?
• What are some of the issues associated with Visual Studio .NET?
• Is National Instruments integrating .NET technology into its products?
• How might Visual Studio .NET affect my current development efforts?
• How might Microsoft .NET affect the measurement and automation industry?

What is the .NET Framework?


The .NET Framework consists of framework base classes that are extended to support
the Web Services, Web Forms, and Windows Forms technologies. The .NET
Framework provides a strongly typed object foundation, and Microsoft plans to supply
many fundamental classes inside the framework for creating .NET applications. Using
the .NET Framework, you can create distributed Web services in the same way that
you currently create Windows applications. The Common Language Runtime (CLR) is
the underlying foundation for the .NET Framework. The CLR is a multi-high-level
language execution engine that provides a solid foundation for .NET developers to build
many types of applications.
What is the Common Language Runtime (CLR)?
Studio .NET languages, such as Visual Basic .NET, Visual C#, and Visual C++, are built
on. Because of the CLR, you can easily interchange components between the
languages and take advantage of the following benefits:
· Integration of code written in different .NET languages
· Security with code identity
· Deployment eliminating problems with shared components
· Versioning of reusable components
· Reuse through implementation inheritance
· Object lifetime management
· Self-describing objects
What are the changes to the Visual Basic programming language?
Visual Basic .NET is designed to be the easiest and most productive tool for creating
.NET applications, including Windows applications, Web Services, and Web
applications. While the Visual Studio .NET development environment is similar to the

Вам также может понравиться