Home > 2010 Winter BTI420 > Getting started with ASP.NET Membership, Roles, and Profiles

Getting started with ASP.NET Membership, Roles, and Profiles

February 10, 2010 Leave a comment Go to comments

ASP.NET membership gives you a built-in way to validate and store user credentials. In this post, you will set up and configure its database objects.

 

Using ASP.NET Membership, Roles, and Profiles

It’s time to look at ASP.NET Membership, Roles, and Profiles. (Today, we will look only at Membership and Roles, and later we’ll add Profiles.)

From the Introduction to Membership document:

 
ASP.NET membership gives you a built-in way to validate and store user credentials. ASP.NET membership therefore helps you manage user authentication in your Web sites. You can use ASP.NET membership with ASP.NET Forms authentication or with the ASP.NET login controls to create a complete system for authenticating users.

Membership helps with user account management and authentication. We will also use Roles to help with authorization (i.e. allowing users to access resources).

From the Understanding Role Management document:

 
Role management helps you manage authorization, which enables you to specify the resources that users in your application are allowed to access. Role management lets you treat groups of users as a unit by assigning users to roles such as manager, sales, member, and so on. After you have established roles, you can create access rules in your application. For example, your site might include a set of pages that you want to display only to members. Similarly, you might want to show or hide a part of a page based on whether the current user is a manager.

Using Membership and Roles enables you to build a web site with robust user account management and authentication features. Little or no code is required to implement Membership and Roles.

Today, we will go through the following steps to implement Membership and Roles on a new web site. Although we need only Membership, we will also configure Roles so that we can have a standard web site "member" role, and an "administrator" role. Here are the steps:

  1. Add the necessary tables to your personal database
  2. Configure your Web.config for Forms Authentication
  3. Configure your Web.config with the Membership and Roles providers
  4. Add the Member and Administrator roles
  5. Add YOUR user account as an administrator
  6. Add folders and web forms to your web site
  7. Configure your Web.config with authorization (access) rules
  8. Add a "new user creation" web form
  9. Add login controls to a page (or master page)
  10. Configure navigation, and enable "security trimming"

This work will require a couple of hours to complete. For best results, read/skim through all of the steps before starting to perform them.

 

Step 1 – Add the necessary tables to your personal database

In this step, we will add the necessary tables to your personal database on mssql.warp.senecac.on.ca. To get started, login to a Windows computer (your own computer, or one at the College). Then, navigate to this folder:

C:\Windows\Microsoft.NET\Framework\v2.0.50727

Run the aspnet_regsql.exe program. (Alternatively, Start > Run "C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe".)

The "ASP.NET SQL Server Setup Wizard" starts.

On the "Select a Setup Option" panel, choose "Configure SQL Server for application services" and click the Next button.

On the "Select the Server and Database" panel, specify the mssql.warp.senecac.on.ca server, and YOUR credentials and database name. Then, click the Next button.

On the "Confirm Your Settings" panel, confirm, and then click the Next button. After a few seconds, the wizard shows you the completion message.

At this point in time, you can use Visual Studio’s database tools, or SQL Server Management Studio, to view the resulting tables.

 

Step 2 – Configure your Web.config for Forms Authentication

In this step, we configure Web.config for Forms Authentication.

Locate the existing "<authentication…" element. By default, its mode is "Windows", which is a good setting for enterprise/intranet web apps. We have to change this to support our public-facing web app.

Edit your authentication element so that it looks similar to the following. A few notes:

  • The ~/login.aspx refers to a web form that we will create
  • Replace ".yourUniqueAppName" with a string to uniquely identify your web site; we suggest using part of your name and your warp account name together
<authentication mode="Forms">
    <forms name=".yourUniqueAppName" loginurl="~/login.aspx" />
</authentication>

 

Step 3 – Configure your Web.config with the Membership and Roles providers

In this step, we configure Web.config with the Membership and Roles providers. These are elements that enable ASP.NET Membership and Roles to work properly.

First, make sure there’s a valid "connection string" to your personal database in Web.config.

 
What is a "connection string"?

A connection string contains the information needed for a web app to connect to a database. It includes:

  • A connection string "name" to identify this specific connection string; this name is used elsewhere in Web.config, and in your classes
  • The kind of database server to connect to (e.g. Microsoft SQL Server)
  • The location of the database server, in the form of a fully-qualified name/identifier
  • The name of the database to connect to
  • Credentials (user name and password)

There are (at least) two ways to create a connection string:

  1. Type it in yourself, or…
  2. Create a throw-away web form. Drag any table from your database to the design surface. Save the web form – this action writes a connection string to Web.config. (Then, you can delete the throw-away web form.

Where is the connection string located? Inside the "configuration" element. We suggest that you place the connection string near the beginning of the configuration element.

Your connection string may look similar to the following. A few notes:

  • Replace "name" string with your own identification string
  • Replace the "Initial Catalog" database name with your own database’s name
  • Replace the credential strings with your own credentials
<connectionStrings>
    <add name="a03" connectionString="Data Source=mssql.warp.senecac.on.ca;Initial Catalog=bti420_101a03;Persist Security Info=True;User ID=myWarpDatabaseAccountName;Password=myWarpDatabaseAccountPassword"
  providerName="System.Data.SqlClient" />
</connectionStrings>

Now, add the "membership" element. Place it just below the "authentication" element that you just added earlier. You can copy the following (as plain text; hover over it for a pop-up toolbar), and paste it into your own Web.config – but you must change the "connectionStringName" to match your own connection string name. 

<membership defaultProvider="SqlProvider" >
  <providers>
    <clear/>
    <add
      name="SqlProvider"
      type="System.Web.Security.SqlMembershipProvider"
      connectionStringName="a03"
      applicationName="/"
      enablePasswordRetrieval="false"
      enablePasswordReset="true"
      requiresQuestionAndAnswer="true"
      requiresUniqueEmail="true"
      passwordFormat="Hashed" />
  </providers>
</membership>

Next, add the "Roles" element. Place it just below the "membership" element. You can copy the following and pate it into your own Web.config- but you must change the "connectionStringName" to match your own connection string name. 

    <roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider">
      <providers>
        <clear/>
        <add name="AspNetSqlRoleProvider"
          connectionStringName="a03"
          applicationName="/"
          type="System.Web.Security.SqlRoleProvider"/>
      </providers>
    </roleManager

Save your Web.config changes. Close Web.config.

 

Step 4 – Add the Member and Administrator roles

In this step, we manually create the Member and Administrator roles.

This is a one-time operation.

Create a throw-away web form (it doesn’t matter what its name is). In the web form’s C# code behind, in the Page_Load method, add the following code, which creates the two roles:

    protected void Page_Load(object sender, EventArgs e)
    {
        System.Web.Security.Roles.CreateRole("Member");
        System.Web.Security.Roles.CreateRole("Administrator");
        Response.Write("Done");

    } // Page_Load

Run the page. When it completes, it will display "Done". Use Visual Studio’s database tools (or SQL Server Management Studio) to verify that the aspnet_Roles table was updated (there should now be two rows of data), then delete this code.

 

Step 5 – Add YOUR user account as an administrator

In this step, we manually create YOUR user account, and ensure that it’s in the administrator role. (Again, we must do this manually.)

This is a one-time operation.

The previous step instructed you to delete the role-creation code. Make sure it’s gone. Then, add the following code (replacing the generic data with your own!). Make sure the password that you use is at least seven (7) characters in length, and it must include a non-alphanumeric symbol (like a ! or a #):

    protected void Page_Load(object sender, EventArgs e)
    {
        System.Web.Security.MembershipCreateStatus status;

        // Replace the generic data with your own...
        System.Web.Security.Membership.CreateUser
            ("yourAccountName", "yourPassword", "yourEmailAddress",
            "security question", "security answer", true, out status);
        System.Web.Security.Roles.AddUserToRole
            ("yourAccountName", "Administrator");
        Response.Write("Done");

    } // Page_Load

Run the page. When it completes, it will display "Done". Now, look at the aspnet_Users and aspnet_UsersInRoles tables, to verify that they were updated (each table should now have one row of data). You can now delete this throw-away web form.

 

Step 6 – Add folders and web forms to your web site

websitestructure In this step, you will create a folder and web form structure for your web site. The suggestions will enable easy and automatic user account management, authentication, and authorization as you begin work on your assigned web site reorganization in the next few weeks.

Refer to the diagram at the right. There are a number of folders and items, briefly described below.

In your "ui/mp" folder, create another master page. For all new web forms (except labs), you will begin using this new master page.

 
Spend a few minutes now to edit this new master page. You will use it now, and in future steps.

Create a folder that will hold administrator-only content (e.g. "admin"). After configuring authorization, this folder will be available ONLY to the administrator user created earlier (YOU!). Create default.aspx (and use your new master page) so that we can test whether you have done the work correctly.

Create a folder that will hold member-only content (e.g. "member"). After configuring authorization, this folder will be available ONLY after a successful login. Create one or more web forms (and use your new master page) so that we can test whether you have done the work correctly.

Create a "public" folder. All users – even anonymous users – will have access to the items in this folder. Create one or more web forms (and use your new master page) so that we can test whether you have done the work correctly.

In the web site root, create login.aspx (and use your new master page). After configuring authorization, this page will be shown whenever a browser user requests a page that they are not yet authorized to view.

You will already have a "labs" folder that holds your labs. You probably also have a "testing" folder for testing and throw-away items. Finally, you also probably have an "assets" folder that digital assets (page content).

Before you go on, browse around to ensure that you can access the web pages, particularly those which are in folders that will be protected with authorization rules (in the next steps…).

 

Step 7 – Configuring Web.config with authorization (access) rules

In this step, we configure Web.config with authorization access rules:

  • Only an "Administrator" can access resources in the "admin" folder
  • Users logged in as "Member" or "Administrator" can access resources in the "member" folder
  • By default, access to all other resources is permitted to any user

Add this code block. Place it in the "configuration" element. We suggest placing it near the bottom. You can copy the following (as plain text; hover over it for a pop-up toolbar), and paste it into your own Web.config.

  <!-- BEGIN location elements for authorization rules 
  
  Place this code block in the configuration element, near the bottom
  
  Authorization rule processing is done in sequence, from top to bottom
  Rule processing ends when the first matching rule is found
  A question mark ? denies anonymous users 
  An asterisk * denies all users -->

  <location path="admin">
    <system.web>
      <authorization>
        <allow roles="Administrator"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>

  <location path="member">
    <system.web>
      <authorization>
        <allow roles="Member,Administrator"/>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>
  
  <!-- END location elements for authorization rules -->

Before you go continue with the next step, browse around to ensure that the access rules were configured correctly. Accessing web pages that are in the "member" and "admin" folders will actually redirect to your login.aspx page. Test to make sure this happens.

 

Step 8 – Add a "new user creation" web form

In this step, we modify the "createuser.aspx" web form to add the CreateUserWizard login web server control.

From the toolbox’s "Login" group, drag a CreateUserWizard login web server control to your web form.

We need to make a coding change for best results: When a new user account is created, we need to put the user in the "Member" role. Therefore, do this:

  1. Click/select the CreateUserWizard control, and then show its properties.
  2. On the properties toolbar, click the Events icon (the lightning bolt).
  3. Double-click the CreatedUser action/event, and it will create a method stub in the C# code behind.

In the "using…" area, add "using System.Web.Security;" to bring that namespace into scope.

Then, add the following code to the just-created method stub:

    protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
    {
        // This event fires AFTER the user was successfully created
        // It adds the new user to the "Member" role

        // Add the user to the role...
        Roles.AddUserToRole(CreateUserWizard1.UserName, "Member");
        // Redirect the user to the welcome page
        Response.Redirect("~/public/welcome.aspx");

    } // CreateUserWizard1_CreatedUser

Test this web form, by running it, and adding a new user account.

 

Step 9 – Add login controls to your master page

In this step, we modify the new master page you added in Step 6 above, and add some login web server controls to it.

Decide where you want the login controls to appear. Top? Left side? Bottom? Then, drag a Login web server control to your master page. I would suggest that you set the "VisibleWhenLoggedIn" property to False.

Then, drag a LoginStatus web server control, and position it just below the Login control. Open its properties, and change its appearance to suit your needs. (For example, the "LoginText" property should be blank/empty. Why show anything here if you’re already showing the Login web server control?)

Then, drag a LoginView web server control to somewhere else on the page (maybe the footer). Configure its templates to show appropriate content. For best results, do this in markup/source view; see below for an example.

    <asp:LoginView ID="LoginView1" runat="server">
        <AnonymousTemplate>
            <p>
                You are not logged in</p>
            <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="public/createuser.aspx">Click here to create an account</asp:HyperLink>
        </AnonymousTemplate>
        <LoggedInTemplate>
            <p>
                This content is special, and is shown only to authenticated users</p>
        </LoggedInTemplate>
    </asp:LoginView>

Test your results by navigating around your web site. Test thoroughly.

 

Step 10 – Configure navigation, and enable security trimming

In this last step, we add an ASP.NET navigation control (in this example, a menu). We then configure it so that it shows only the menu items that are available to the authenticated user.

( moved to separate blog post, and it will be posted during week 7 )

 


Advertisements
Categories: 2010 Winter BTI420
  1. Gray
    July 16, 2010 at 10:21 am

    Hi Peter,

    I can’t get this example to work. What code do I need to write in my ~/Login.aspx file? Only I don’t think this example will work unless the Login.aspx page knows where to look for the security members database.

    Can you please clarify?
    Many thanks,
    Gray.

    • petermcintyre
      August 23, 2010 at 4:47 pm

      Sorry for the response delay (vacation). The default login control uses Web.config settings to locate the membership database. Therefore, if you follow the sequence, including the Web.config changes, it will use the database that you would have installed in Step 1. Hope this helps.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: