Exercise 1: Application Security
This exercise will add authentication and role-based authorization to an already existing application.
First step
To hit the BugSmak.sln project, the default installation path should be C:\Program Files\Microsoft Enterprise Library January \begin, and compiled.
The second step is to add authentication to the application
1. Select Debug | The Start without Debugging menu command runs the application. The application currently has no authenticated users to use.
2. Closes the application.
3. Select Security \ SecurityHelper.cs file in Solution Manager, select View | Code menu command, add the following namespaces.
Using System.Web.Security;
4. Add the following code to the method authenticate.
public static bool Authenticate(string username, string password)
{
bool authenticated = false;
// TODO: Authenticate Credentials
authenticated = Membership.ValidateUser(username, password);
// TODO: Get Roles
return authenticated;
}
The method authenticate will be called by the form LoginForm to authenticate the user, and the Membership.ValidateUser method implements the user's authentication. The membership system uses the Provider model, so the application does not need to implement data storage, ASP.net ships provides two membership Provider, one using Microsoft SQL Server as the data source, The other is using Windows Active Directory. You can also create your own membership Provider that we have implemented read from the XML file to read the application members.
5. Select Security in Solution Manager | Providers | ReadOnlyXmlMembershipProvider.cs, and choose View | The Code menu command reviews the codes.
Readonlyxmlmembershipprovider (inherited from MembershipProvider) is a custom provider example that implements reading from an unencrypted XML file, which is not a good practice, But it's very useful in this exercise.
6. Open the App.config file to view the configuration of the membership provider, and the storage of the certified data is defined in a Users.xml file.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<membership defaultProvider="ReadOnlyXmlMembershipProvider">
<providers>
<add name="ReadOnlyXmlMembershipProvider"
type="BugSmak.Security.Providers.ReadOnlyXmlMembershipProvider, BugSmak"
description="Read-only XML membership provider"
xmlFileName="Users.xml" />
</providers>
</membership>
<roleManager enabled="true"
defaultProvider="ReadOnlyXmlRoleProvider">
<providers>
<add name="ReadOnlyXmlRoleProvider"
type="BugSmak.Security.Providers.ReadOnlyXmlRoleProvider, BugSmak"
description="Read-only XML role provider"
xmlFileName="Users.xml" />
</providers>
</roleManager>
</system.web>
</configuration>
If you have a custom provider, you must configure your application.