Skip Navigation LinksHome : CBC Classes : ASP.Net : Security & Membership

CS218 ASP.Net - Security & Membership (Logging In)

  1. The security and membership concept (video)
  2. Membership Setup now that ASP uses Identity
    1. Add a login page with login control
    2. Manually start the Web Server and Admin Tool (video, code)
  3. Setup -
    1. All the steps with detailed explanation (video, video, video)
    2. All the steps in a brief video and no explanation. (video)
    3. Youtube Video Tutorial - Configuring security with the wizard
    4. See all the database items that have been created and be thankful you don't have to do this yourself (video)
  4. Editing security settings
    1. How folder access is controlled with web.config (video)
    2. Running the web configuration tool, but not using the wizard (video)
  5. Roles
    1. Why use roles and adding users to a role (video)
    2. Managing Roles, adding permissions to a role via web configuration tool and by editing web.config(video)
  6. Hiding Menu Items (video, code)
  7. Fixing the disappearing menu trick (code)
  8. Using the asp:loginStatus control to add a login button or link (video)
  9. Using the asp:loginView and asp:loginName controls to build a better loginStatus(video)
  10. The Other Login Controls
    1. Video Tutorial - - The login status control
    2. LoginView
    3. LoginStatus & LoginName
    4. PasswordRecovery Wizard
    5. ChangePassword Wizard
    6. CreateUserWizard
  11. Location of login.aspx set in web.config
  12. Changing password strength
  13. Changing the timeout delay (video, code)
  14. Choosing encryption type
  15. Setting project name for encryption
  16. Using Membership and Security on a production server like GoDaddy
  17. Other Resources

Other Resources

  1. The MSDN Forms Element Pages All of the settings for the <forms> in the web.config
  2. Examining ASP.NET's Membership, Roles, and Profile By Scott Mitchell (4GuysFromRolla) This is a great, very comprehnsive set of articles on Membership.

Changing or Setting the timeout delay

Now that Microsoft has switched to using Identity instead of Membership, they also took away the ability to easily run the Membership Administration Web Tool. You can still run it, but you have to do some manual setup.

  1. The first step is to start the web server manually, and tell it to use the Web Based Admin Tool. Starting the web server requires opening a CMD window, and moving to the directory that holds the exectuable code for the web server.
    1. Open a CMD window
    2. Type: cd \program files\iis express
    3. Copy and paste the following code: (You have to right-click to paste it, <ctrl-v> won't work)
      iisexpress.exe /path:C:\Windows\Microsoft.NET\Framework\v4.0.30319\ASP.NETWebAdminFiles /vpath:/ASP.NETWebAdminFiles /port:8080 /clr:4.0 /ntlm
      You should see something like the following that indicates the web server is now running:
      picture of web server start messages
    4. Leave the web server running while you complete the remaining steps. When you're completely done setting up Membership you can come back to the CMD window and hit Q to stop it.
  2. The next step is to start a web browser, then provide it the URL that points to the Web Administration Tool.
    1. Open Notepad and paste the following text:
    2. You have to modify this by replacing [appPath] with the path to your web site files, that is the folder that holds the web site that you're adding Membership to. That path is typically going to be something like:
      C:\Users\Username\My Documents\Visual Studio 2013\WebSites\WebsiteName
      The easiest way to get this, and avoid typing errors is to start Windows Explorer, navigate into the folder that holds the web site, then right click on the address bar and select Copy Address As Text
    3. Return to Notepad and replace [appPath] with the path to your web site. Be careful when you paste this, don't overwrite the = on the left or the & on the right.
    4. Copy everything in Notepad, the entire modified URL.
    5. Start your favorite web browser. Paste the modified URL in the location dialog box. This will start the Web Administration Tool. You're now ready to administer the web site, create users and apply permissions.

Changing or Setting the timeout delay

The timeout delay controls how long a user can be inactive before being automatically timed out. This is set in the authentication section of the site's main web.config. The default value is 30 minutes. To change it add the new value in the <forms> tag. The following example sets it to 45 minutes.

  <authentication mode="Forms">
      <forms timeout="45" />

Note - the way the user's activity is calculated may make this number a little imprecise. It will be close, but it won't be exactly the number you set. You can read all of the gory details at MSDN.

Location and name of login.aspx file

One of the key components to making Membership and Security work is the login.aspx file. If a user tries to access a page and doesn't have permission ASP will redirect them to the login.aspx page. By default this page will be in the root folder for your project/web site; but you can move it or rename it if you wish. If you do move it, you'll have to let ASP know where it is. This is done by adding loginURL attribute to the <forms /> tag in the authentication section of the site's main web.config. For example, the following code uses the file ~/loginFolder/mainLogin.aspx as the login page for the site.

  <authentication mode="Forms">
      <forms loginURL="~/loginFolder/mainLogin.aspx" />

Note - the way the user's activity is calculated may make this number a little imprecise. It will be close, but it won't be exactly the number you set. You can read all of the gory details at MSDN.

Hiding menu items from users w/o permission to see them

A great feature of ASP Security and Membership is the way it's tied together with the ASP menus. You can set it up so that menu items will be hidden from users that don't have permission to access the corresponding page(s). And as soon as the user logs in, the menu items will automatically be displayed. Setting this up is so simple that you will probably take for granted how much coding it would take to accomplish if you had to do it yourself. Make sure and read the next section too, because it's become a little harder to make this work.

This is set up by adding the following <sitemap>section to your site's main web.config. As noted it needs to go inside the <system.web> start and end tags.

<!-- other configuration settings -->
  <siteMap defaultProvider="XmlSiteMapProvider" enabled="true">
      <add name="XmlSiteMapProvider"
        description="Default SiteMap provider."
        type="System.Web.XmlSiteMapProvider "
        securityTrimmingEnabled="true" />

Fixing menus that disappear when security trimming is enabled

Sometimes setting securityTrimming causes all the menus except the top one to disappear. This can be caused by a couple of things, but basically it comes down to the way security trimming works. The algorithm compares each directory in the web.sitemap file with the various web.config files to decide whether it should display the menu items. The problem occurs when you don't want the top level menu to display, or point to any file. (I've always thought that having that one top level Home menu item was awkward.) If you leave the url attribute for the siteMapNode blank then the security trimming algorithm breaks down, as it doesn't have a file to check. When it performs the check, it fails, so it decides that you don't have permission to see this node or any of it's children. And since it's the top level node, all of the children disappear as well.

In 2015 we ran into a new problem, that the old method partially fixed. The fix requires these steps:

  1. Ensure that you have roles enabled, and you have at least one role setup. This means you may have to run the Web Admin Tool again if you didn't setup roles before. (I know it's a pain, but there's no way around it.) For example, make a role named Admin.
  2. Before you close the Web Admin Tool, add any users you want to see the menu to the role. Even if you only want a single user to have access to a folder, you're going to have to add the user to the role. For example, I would add any users I want to access my secure folder(s) to the Admin role.
  3. Open your Web.Sitemap file and add roles="*" to the top level siteMapNode, and all of the parent siteMapNodes that you want to be visible to anonymous users. Ensure that you add this to the outermost siteMapNode.
    Add roles="roleName" to the top level siteMapNode of any menu sections you want to hide from anonymous users, but make visible to logged in users.
    In this example code the Guitars and Keyboards menu items are visible to everyone, while the Owner section of the menu is only visible to members of the Admin role.
            <siteMap xmlns="" >
                <siteMapNode url="default.aspx" title="Home" roles="*" description="">
                <siteMapNode url="" title="Guitars" roles="*"  description="">
                  <siteMapNode url="~/guitars/fender.aspx" title="Fender"  description="" />
                  <siteMapNode url="~/guitars/gibson.aspx" title="Gibson"  description="" />
                <siteMapNode url="" title="Keyboards" roles="*"  description="">
                  <siteMapNode url="~/keys/yamaha.aspx" title="Yamaha"  description="" />
                  <siteMapNode url="~/keys/nord.aspx" title="Nord"  description="" />
                <siteMapNode url="" title="Owner" roles="Admin"  description="">
                  <siteMapNode url="~/secret/changePrices.aspx" title="Change Prices"  description="" />
                  <siteMapNode url="~/keys/addEquipment.aspx" title="Add Equipment"  description="" />

There are a couple of solutions to this. The first is to add roles="*" to the top level siteMapNode tags of all the . This says to give all roles permission to see this node, kind of like adding the permission to the main web.config for the web site. The second is to set the url attribute in the top level siteMapNode to ~/. This way there's a directory for the security trimming algorithm to use, and it should return a true value which will allow the user to see all the menus they have permission to see.

<?xml version="1.0" encoding="utf-8" ?>
<siteMap  enableLocalization="true" xmlns="" > 
    <siteMapNode url="" title="" roles="*"  description=""> 
      <siteMapNode url="~/default.aspx" title="Home" description="" /> 


<?xml version="1.0" encoding="utf-8" ?>
<siteMap  enableLocalization="true" xmlns="" > 
    <siteMapNode url="~/" title="" description=""> 
      <siteMapNode url="~/default.aspx" title="Home" description="" /> 

Create User Wizard

If you just want to add users, the CreateUserWizard can simply be dropped on a page and it will do the job. But often times you want to add another step, such as adding the new user to a role.

<asp:WizardStep ID="WizardStep1" runat="server" AllowReturn="False" 
   Select one or more roles for the user:
  <asp:ListBox ID="AllRoles" runat="server" SelectionMode="Multiple" >


The VB Code

    Protected Sub BuildRoleList(ByVal sender As Object, ByVal e As System.EventArgs)
        ' This code gets all of the roles and adds them to the listbox in the createuserwizard.
        ' The name of this subroutine must match the subroutine you call in the onActivate property of the wizardStep
        ' The only thing you need to change is AllRoles, which must match the id of your listbox. 
        AllRoles.DataSource = Roles.GetAllRoles()
    End Sub

    Protected Sub AssignUserToRoles(ByVal sender As Object, ByVal e As System.EventArgs)
        ' This code adds theuser to all selected roles from the listbox in the createuserwizard
        ' The name of this subroutine must match the subroutine you call in the onDeactivate property of the wizardStep
        ' The only things you need to check or change are AllRoles, which must macth the id of your listbox, and 
        ' CreateUserWizard1, which must match the name of your createuserwizard
        Dim tmpItem As ListItem

        For Each tmpItem In AllRoles.Items
            If tmpItem.Selected = True Then
                Roles.AddUserToRole(CreateUserWizard1.UserName, tmpItem.ToString)
            End If

    End Sub