Now, we need to make a change to the web.config file concerning authentication.
Listing 6: Authentication Section
<authentication mode="Forms">
<forms loginUrl="CustomFormAuthentication\Login.aspx"
timeout="60"
protection="All"
slidingExpiration="true"/>
</authentication>
Create a new Web form and name it Default.aspx, performing the following actions:
- Drag and drop a LoginView control onto the form.
- Drag and drop a LoginStatus control into the LoginView Control.
Figure 12: Example Default.aspx Web Form
Now run your application and you will be presented the above screen in your browser. Click Login and ensure you can in fact successfully login to the application. If so, you should be returned to Default.aspx, and the LoginStatus control will now reflect your username along with an option to logout of the application.
Role Management
Apart from user authentication, most applications require some sort of role-based authorization. The role manager also uses some kind of provider to store the information related to roles and their mappings to users.
The machine.config file contains the default settings. To customize these setting all you need to do is modify your web.config.
Listing 7: Roles Configuration
<configuration>
<connectionStrings>
<add name="SqlServices" connectionString=
"Data Source=servername;Initial Catalog=databasename;
Integrated Security=SSPI;" />
</connectionStrings>
<system.web>
<authentication mode="Forms" >
<forms loginUrl="login.aspx"
name=".ASPXFORMSAUTH" />
</authentication>
<roleManager defaultProvider="SqlProvider"
enabled="true"
cacheRolesInCookie="true"
cookieName=".ASPROLES"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All" >
<providers>
<add
name="SqlProvider"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="SqlServices"
applicationName="SampleApplication" />
</providers>
</roleManager>
</system.web>
</configuration>
Some of the more important methods of the Roles class are as follows:
- CreateRole: Used to create a new role.
- GetAllRoles: Used to get all existing roles. It returns an array of strings.
- AddUserToRole: Adds a user to a role.
- RemoveUserFromRole: Removes a user from a role.
- IsUserInRole: Checks if a user belongs to a role.
- GetRolesForUser: Gets all roles for a particular user. It returns an array of strings.