Authenticated Web Slices
Authenticated Web Slices
Web Slices allow you to subscribe to parts of a Web page and view updates directly from the Internet Explorer Favorites bar. To learn how to create Web Slices, refer to Subscribing to Content with Web Slices. This topic covers the security model of Web Slices and includes samples of authenticated scenarios in ASP.NET.
This topic contains the following sections:
- Web Slices: Security Modes
- DEMOS
- DEMO 1 — Using cookies to store user profile
- DEMO 2 — Using cookies to store user credentials (ASP.NET Membership)
- DEMO 3 — Using HTTPS+Digest on IIS to secure the Web Slice
- Related Topics
Web Slices: Security Modes
Web Slices can leverage some of the security features of a standard Web page or Really Simple Syndication (RSS) feed. Many scenarios require some sort of security layer to authenticate the user; by remembering credentials across different browsing sessions, a Web Slice becomes more user-friendly. For example, a Web Slice could automatically supply a username and password in order to retrieve email from a Web server.
Web Slices in Internet Explorer 8 can authenticate to their Web site using any of the following:
- Cookies
- HTTPS + Basic
- HTTP + Digest
- HTTPS + Digest
DEMOS
You will find three different demos attached to this article, one for each of these scenarios. In order to run and build the samples, you will need to install one or more of the following:
- Visual Studio Web Developer 2008 Express Edition
- SQL Server 2008 Express Edition
- The IIS 6.0 Resource Kit Tools
DEMO 1 — Using cookies to store user profile
Cookie-based authentication is broadly supported and works regardless of the security settings of the Web Slice. You can use cookies to store non-sensitive information, user preferences, Web Slice settings, and so on. In this sample we use cookies to store the user profile in the Web site and later retrieve the same information from within the Web Slice. For more information, please refer to ASP.NET Cookies Overview overview.
Download source code: StoringProfile.zip
The Web Slice in this demo uses an alternative display view. This allows us to render different content in the Web Slice preview window. Although this demo has been built by using ASP.NET 3.5, you can adapt this concept to any other Web technology or language.
- web.config contains site settings.
- Default.aspx is the page loaded by the browser.
- WebSlice.ascx represents the drop-down control used to select a color.
- DisplayPage.aspx is the alternative display source for the Web Slice.
- DisplayWebSlice.ascx renders the Web Slice content by reading the cookie and setting the background color.
- ProfileProvider.cs defines a custom class that reads and writes the color value to the user's profile (in this case, a cookie).
- CookieHelper.cs simplifies the process of storing and retrieving values from a cookie.
In order to make a cookie persistent across different browser sessions, you need to specify the cookie's expiration, such as:
public static void WriteCookie(HttpCookie cookie)
{
if (cookie != null)
{
cookie.Expires = DateTime.Today.AddDays(31);
HttpContext.Current.Response.Cookies.Add(cookie);
}
}
Likewise, to delete a cookie, subtract a year from its expiration date. The CookieHelper
class (Figure 1) encapsulates these actions to allow you to more easily read, write, and delete cookies.
Figure 1: CookieHelper class definition
The ProfileProvider
class simplifies the interaction with the CookieHelper
class by providing two methods: GetColor and SaveColor. When the user selects a color from the drop-down list on the main page (Figure 2), ASP.NET will save the user preference inside a cookie with an expiration time of 31 days with the following code in Webslice.ascx.cs:
protected void ddlColors_SelectedIndexChanged(object sender, EventArgs e)
{
var color = ddlColors.SelectedValue;
if (color != null)
{
ProfileProvider.SaveColor(color);
panel.BackColor = Color.FromName(color);
}
}
Figure 2: Saving profile on the Web page
As soon as the user adds the Web Slice to Internet Explorer 8, ASP.NET will:
- Load the content from the display source.
- Read the value of the cookie.
- Render the HTML snippet dynamically (as in Figure 3).
The background color of the Web Slice is set by DisplayWebSlice.ascx.cs:
protected void Page_Load(object sender, EventArgs e)
{
var color = ProfileProvider.GetColor();
if (color != null)
{
lblColor.Text = color;
WebSlice_StoringProfile.Style["background-color"] = color;
}
}
Figure 3: Reading profile from the Web Slice
You have full control over cookies from the Web Slice code; however, you should avoid storing username and passwords in plain text inside a cookies, as cookies can be easily modified or attached from a malicious user.
The next scenario demonstrates how to save sensitive information more securely.
DEMO 2 — Using cookies to store user credentials (ASP.NET Membership)
Cookie-based authentication is flexible and easy to implement; however, you should not save any sensitive information (for example, username and password) in plain text in order to avoid security prompts.
Download source code: FormsAuthentication.zip
In this sample, we will use ASP.NET Membership to store the user credentials. For the sake of this demo, we consider an e-mail scenario where the user needs to authenticate with the Web server in order to see his e-mails.
- web.config contains site settings.
- Default.aspx is loaded in the browser.
- WebSlice.ascx contains an e-mail inbox control.
- EmailInBox.ascx uses templates to determine if the user is authenticated.
- LoginCustomControl.ascx is the login form.
- DisplayPage.aspx is the alternative display source for the Web Slice.
- DisplayWebSlice.ascx also contains the e-mail inbox control.
- AuthenticationHelper.cs checks credentials and creates a membership "ticket."
- EmailsProviders.cs creates a few empty messages for display.
Figure 4: Authenticated Web Slice displaying inbox
ASP.NET Membership gives you a built-in way to validate and store user credentials in a secure way using an encrypted cookie. This solution is safe and it doesn't expose the user personal information to a potential attacker. For more information, please refer to Introduction to Membership.
The first step is to set up Forms Authentication for our Web site, using the ASP.NET Configuration Tool to generate the database for our application. In the sample provided, the database has been already populated with the following user:
- Username: username
- Password: Passw0rd!
The Web.Config file has been customized to override the default LoginUrl
and Timeout
. Users can stay logged in to the application for 30 days.
<authentication mode="Forms">
<!-- 30 days = 43200 minutes -->
<forms
loginUrl="Default.aspx"
protection="All"
timeout="43200"
name=".ASPXAUTH"
path="/"
requireSSL="false"
slidingExpiration="true"
defaultUrl="Default.aspx"
cookieless="UseDeviceProfile"
enableCrossAppRedirects="true"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
Because of this configuration, the Web site will redirect any non-authenticated user to the login page (Default.aspx).
The second step is to add a login form to the default page. The Microsoft .NET Framework offers a set of Login controls that allow the developer to easily use the Membership provider without writing any line of code (Figure 5).
Figure 5: Default login control
In this scenario however we will create a custom login form in order to show the code underlying the login process and to explicitly set the expiration of the authentication cookie (generated by the FormsAuthentication
class).
Note in the LoginCustomControl.ascx.cs:
protected void btnLogin_Click(object sender, EventArgs e)
{
if (AuthenticationHelper.CheckLogin (txtUsername.Text, txtPassword.Text))
AuthenticationHelper.CreateTicket(txtUsername.Text, "");
}
If the CheckLogin
method of the AuthenticationHelper.cs class returns a positive value, the page will proceed storing the user token in an encrypted cookie.
public static void CreateTicket(string username, string customData)
{
// Cookie Expiration.
DateTime expiration = DateTime.Now.Add(TimeSpan.FromDays(30));
FormsAuthentication.Initialize();
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
username,
DateTime.Now,
expiration,
true,
customData,
FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
cookie.Expires = ticket.Expiration;
HttpContext.Current.Response.Cookies.Add(cookie);
FormsAuthentication.RedirectFromLoginPage(username, true);
}
Once authentication is complete, ASP.NET will create a cookie which will remember the user in any successive page request (up to 30 days in this sample) from either the Web Slice or from the Web site.
Finally, the business logic layer of the application will retrieve the current user from the HttpContext and display the user's personal e-mails accordingly.
GridView1.DataSource =
BusinessLogic.EmailsProvider.GetEmails(HttpContext.Current.User.Identity);
GridView1.DataBind();
Note that you should plan to have some content in the Web Slice when the user is not authenticated, such as a link to the login page or registration page.
DEMO 3 — Using HTTPS+Digest on IIS to secure the Web Slice
Web Slices also support HTTP and Secure Hypertext Transfer Protocol (HTTPS) security (basic or digest). If you plan to use this kind of security, please note that these authentication modes are not supported for Web Slices that use an alternative update or display source. For those scenarios, please refer to the previous demos with cookies authentication.
If you are not using an alternative update or display source, you can choose one the following security modes:
- HTTPS + Basic
- HTTP + Digest Authentication
- HTTPS + Digest Authentication
Web Slices in Internet Explorer 8 support natively those security models; you don't need to do any changes to your existing Web site. When the user opens a Web Slice (in an HTTP or HTTPS domain), Internet Explorer 8 will prompt the user with a login box; if the login process is successful, the user credential will be cached in the browser and be available for future sessions.
Download source code: HttpsDigestAuth.zip
In this sample you will learn how to secure a Web site in the localhost by using HTTPS+Digest authentication. The same process is valid when using HTTPS+Basic or HTTP+Digest authentication.
- web.config contains site settings.
- Default.aspx is loaded in the browser.
- WebSlice.ascx contains an e-mail inbox control.
- EmailInBox.ascx displays a databound grid control.
- EmailsProviders.cs creates a few empty messages for display.
The first step is to add a new application to the default Web site in Microsoft Internet Information Services (IIS). You can either choose Add Application from the Web site shortcut menu, or create a new folder and convert it to an application later. The name of our application folder is HttpsDigestAuth
(Figure 6).
Figure 6: HttpsDigestAuth Web site on localhost
The second step, if you don't have one yet, is to add an Secure Sockets Layer (SSL) certificate to the server that is hosting the Web site. In this sample we will create a development local certificate for test purposes only. You will need to run the SelfSSL tool (available in the Windows Server 2008 SDK, or IIS 6.0 Resource Kit Tools).
At a command prompt with elevated administrator privileges, type the following (Figure 7):
Selfssl /T /N:cn="localhost" /V:365
Figure 7: SelfSSL
This command will create a self-signed certificate on the localhost, valid for one year.
Note The certificate just created will be added automatically to the "Trusted Certificates" list and to your IIS settings for IIS server (Figure 8). You can view the installed certificate by using the IIS Management console, shown in the following images.
Figure 8: The localhost Server Certificate
To verify the binding for the HTTPS port, right-click Default Web Site and select Edit Bindings.
Figure 9: Site Bindings dialog box
Finally, enable the Digest Authentication as the only security model (Figure 10) and require SSL for the Web site (Figure 11). You might need to add the Digest Authentication feature to the IIS server before you can continue.
Figure 10: Enabling Digest Authentication
Figure 11: Requiring SSL
Now when you open the Web site, Internet Explorer should prompt the user with a login box and authenticate the user. From the ASP.NET project, you can get a reference to the currently logged user by using the HttpContext
object.
if (HttpContext.Current.User != null)
{
GridView1.DataSource = BusinessLogic.EmailsProvider.GetEmails(
HttpContext.Current.User.Identity);
GridView1.DataBind();
}
To automatically authenticate after adding the Web Slice to the Favorites bar, right-click the Web Slice, select Properties, click the Settings button, and enter a user name and password (Figure 12).
Figure 12: Setting Web Slice properties