Share via


Claims Walkthrough: Creating Forms-Based Authentication for Claims-Based SharePoint 2010 Web Applications Using ASP.NET SQL Membership and Role Providers

Summary:  Learn how to create forms-based authentication for claims-based web applications by using ASP.NET SQL membership and role providers.

Applies to: Business Connectivity Services | Open XML | SharePoint Designer 2010 | SharePoint Foundation 2010 | SharePoint Online | SharePoint Server 2010 | Visual Studio

Provided by:  Andy Li, Microsoft Corporation

Contents

  • Overview of Authenticating Claims-Based Web Applications by Using ASP.NET SQL Membership and Role Providers

  • Step 1: Creating a SharePoint Web Application

  • Step 2: Preparing the Database to Use an ASP.NET Membership and Role Provider for the Web Application

  • Step 3: Configuring a Membership and Role Provider for the SharePoint Web Application

  • Step 4: Adding Users and Roles to the Membership and Role Provider Database

  • Step 5: Testing Forms-Based Authentication

  • Step 6: (Optional) Troubleshooting Configuration and Unhandled Exception Errors

  • Step 7: Viewing the Claims

  • Step 8: Adding More Users and Roles

  • Conclusion

  • Additional Resources

Click to get code Download code: ClaimsWebConfig_MSDNExample.zip

Overview of Authenticating Claims-Based Web Applications by Using ASP.NET SQL Membership and Role Providers

In this walkthrough, you create a claims-based web application by using a Microsoft ASP.NET membership and role provider as the authentication provider.

Forms-based authentication provides custom identity management in Microsoft SharePoint 2010 by implementing a membership provider, which defines interfaces for identifying and authenticating individual users, and a role manager, which defines interfaces for grouping individual users into logical groups or roles.

This article assumes that you are familiar with forms-based authentication. For more information about forms-based authentication, see Forms Authentication in SharePoint Products and Technologies (Part 1): Introduction.

Step 1: Creating a SharePoint Web Application

Note

If you simply copy the command-line command from this article and try to run it, it may give errors. This is because some characters are converted into special characters during formatting. For example, a hyphen sign (-) that you copy from this article may not work correctly in a Command Prompt window.

To create a SharePoint Web application

  1. Browse to the SharePoint 2010 Central Administration page.

  2. In the Application Management section, click Manage web applications.

  3. On the ribbon, click New.

  4. In the Create New Web Application dialog box, under Authentication, click Claims Based Authentication.

  5. In the IIS Web Site section, under Create a new IIS web site, change the Name field to SharePoint – SQL FBA.

  6. Change the Port number to 200.

  7. In the Claims Authentication Types section, do the following:

    • Select Enable Forms Based Authentication (FBA).

    • Clear other authentication modes.

  8. In the membership provider and role manager fields, enter the following names:

    • ASP.NET membership provider name: aspnetmembership

    • ASP.NET role manager name: aspnetrolemanager

      Note

      We have not set up the membership and role providers yet; we will create them in subsequent steps.

  9. Change the URL to: http://intranet.contoso.com:200.

  10. In the Database Name and Authentication section, change the database name to be WSS_Content_200.

  11. Leave other settings as their defaults.

  12. Click OK to create the web application.

Step 2: Preparing the Database to Use an ASP.NET Membership and Role Provider for the Web Application

In this step, we manually prepare the Microsoft SQL Server database for the ASP.NET membership and role providers. There are also tools available for configuring this. We will go through the steps manually so that you have a better understanding of all the provider pieces that are involved in the configuration.

Note

The Microsoft SQL Server membership provider stores user information in a SQL Server database. You can create your SQL Server user store manually by running Aspnet_regsql.exe from the command line. Alternatively, you can run Aspnet_regsql.exe in wizard mode (see ASP.NET SQL Server Registration Tool (Aspnet_regsql.exe)) or use the ASP.NET Configuration tool. You can find the ASP.NET Configuration tool under the Website menu in Microsoft Visual Studio.

To prepare the database to use an ASP.NET membership and role provider for the web application

  1. Start Microsoft SQL Server Management Studio and connect to your local server instance.

  2. Add a new database named aspnetdb_claim, as shown in Figure 1.

    Figure 1. Creating a new database named aspnetdb_claim

    Creating a new database

  3. Use aspnet_regsql.exe to create the membership database. Open a Command Prompt window. Run the following command-line command to change directories to the Microsoft .NET Framework 2.0 directory.

    cd C:\Windows\Microsoft.NET\Framework64\v2.0.50727

  4. Run the following command, as shown in Figure 2.

    aspnet_regsql -S DEMO2010A -E -A mr –d aspnetdb_claim

    -S    Specifies the server. In this example, the server is local.

    -E    Specifies that Windows authentication should be used to connect to SQL Server.

    -A mr   Specifies that the membership and role feature should be added.

    -d    Specifies the database name.

    Figure 2. Creating the membership database by using aspnet_regsql.exe

    Create membership database using aspnet_regsql.exe

  5. Expand the aspnetdb_claim node and verify that all tables are created.

    Figure 3. Expanded aspnetdb_claim node

    Expanded aspnetdb_claim node

  6. Grant database access to your web application AppPool account. Because your web application is using contoso\adminstrator to log on, it should automatically have full access to this database.

Step 3: Configuring a Membership and Role Provider for the SharePoint Web Application

There are three web.config files that you must modify:

  • Central Administration: To allow picking for site collections.

  • Security Token Service: To allow sign in, and for issuing tokens.

  • FBA Web Application: To allow picking on the local web application.

To configure a membership and role provider for the SharePoint Web application

  1. In the web.config file for the SQL forms-based authentication web application, add the following connection string after the closing </configSections> tag.

    Note

    If you paste from the following example, tab or space characters might be added. While modifying web.config, ensure that you do not add any tab characters or space characters.

    After you add the connection string, your web.config file should resemble the following example.

    <connectionStrings>
      <add name="MyLocalSQLServer"
           connectionString="Initial Catalog=aspnetdb_claim;data source=DEMO2010A;Integrated Security=SSPI;" />
    </connectionStrings>
    
  2. Repeat the previous step for the Central Administration website and the SecurityTokenServiceApplication website.

    The SecurityTokenServiceApplication website is located under the SharePoint Web Services website, as shown in Figure 4.

    Figure 4. SecurityTokenServiceApplication website location

    SecurityTokenServiceApplication website location

  3. Return to the forms-based authentication web application website (http://intranet.contoso.com:200), and reopen the web.config file.

  4. Add the following code inside the <Providers> tag, located under the <membership> tag (see Figure 5).

      <add name="aspnetmembership" 
                 connectionStringName="MyLocalSQLServer" 
                 applicationName="MyAppName" 
                 type="System.Web.Security.SqlMembershipProvider, 
                 System.Web, Version=2.0.0.0, Culture=neutral, 
                 PublicKeyToken=b03f5f7f11d50a3a" />
    

    Figure 5. Provider values in the FBA web application web.config file

    Provider values

  5. Add the following role manager element to the <Providers> tag, under the <RoleManager> section (see Figure 6).

            <add name="aspnetrolemanager" 
                 type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
                 connectionStringName="MyLocalSQLServer"
                 applicationName="MyAppName" />
    

    Figure 6. Role manager values in the FBA web application web.config file

    Role manager values

    Note

    The applicationName attribute specifies the application name for our web application; this is the name that the ASP.NET membership and role provider uses to uniquely identify the users.

  6. Repeat step 1 through step 5 in this procedure for both the Central Administration website and the SecurityTokenServiceApplication website.

    Note

    Because the web.config file for the SharePoint security token service (STS) website does not contain the <system.web> section, you must manually add the section. (The SecurityTokenServiceApplication website is located under the SharePoint Web Services website, as shown in Figure 4.) To see an example of the completed web.config files, open the configuration files that are included in the download (Download code: ClaimsWebConfig_MSDNExample.zip) that accompanies this article.

Step 4: Adding Users and Roles to the Membership and Role Provider Database

Next, add users and roles to the membership and role provider database.

To add users and roles to the membership and role provider database

  1. Launch Microsoft SQL Server Management Studio and run the following query against the aspnetdb_claim database, as shown in Figure 7.

    declare @now datetime
    set @now= GETDATE()
    exec aspnet_Membership_CreateUser 'MyAppName','admin1','pass@word1',
        '','admin1@contoso.com','','',1,@now,@now,0,0,null
    

    Figure 7. Querying the aspnetdb_claim database

    Querying aspnetdb_claim database

  2. Run the following query to add the user admin1 to the Admin role, as shown in Figure 8.

    EXEC aspnet_Roles_CreateRole 'MyAppName', 'Admin'
    EXEC aspnet_UsersInRoles_AddUsersToRoles 'MyAppName', 'admin1', 'Admin', 8 
    

    Figure 8. Adding user admin1 to the Admin role

    Adding user admin1 to the Admin role

Step 5: Testing Forms-Based Authentication

Next, test the forms-based authentication.

To test forms-based authentication

  1. On the Central Administration website, under Application Management, click Create site collection.

  2. In the Web Application drop-down list, select the FBA web application http://intranet.contoso.com:200 (see Figure 9).

    Figure 9. Configuring the web application

    Configuring the web application

  3. In the Title field, change the value to FBA Site.

  4. In the User name field, click Browse and then find the user that we added.

  5. Type admin1 in the search box, and then click the search button, as shown in Figure 10.

    Figure 10. People Picker

    People picker

  6. Double-click the admin1 user in the result area. This returns you to the site collection creation page.

  7. Click OK to create the site collection.

  8. Navigate to http://intranet.contoso.com:200. You should see the logon page, as shown in Figure 11.

    Figure 11. Logon page

    Logon page

  9. Type the following credentials, and then click Sign In.

    • User name: admin1

    • Password: pass@word1

  10. After you log on, notice that the user name in the top-right corner shows as admin1, as shown in Figure 12.

    Figure 12. SharePoint site after the user admin1 is authenticated

    SharePoint site after user admin1 is authenticated

Step 6: (Optional) Troubleshooting Configuration and Unhandled Exception Errors

Figure 13 shows the error that you see if the wrong configurations are entered in the web.config file. Remember that you must edit all the web.config files for all SharePoint processes. The download that accompanies this article contains three web.config files for you to reference. Figure 14 shows an unhandled exception error.

Figure 13. Membership provider configuration error

Membership provider configuration error

Figure 14. Unhandled exception error

Unhandled exception error

If you get an unhandled exception error, you must add the includeExceptionDetailInFaults value to the <serviceBehaviors> section, as shown in the Figure 15.

Figure 15. Adding the includeExceptionDetailInFaults in the <serviceBehaviors> section

Adding includeExceptionDetailInFaults value

Step 7: Viewing the Claims

Next, view the claims.

To view the claims

  1. Create a Web Part and replace the RenderContent function with the following code. You may need to add a reference to Microsoft.IdentityModel.dll and add the namespace Microsoft.IdentityModel.Claims.

            protected override void RenderContents(HtmlTextWriter writer)
            {
                try
                {
                    IClaimsIdentity currentIdentity = System.Threading.Thread.CurrentPrincipal.Identity as IClaimsIdentity;
                    writer.Write("---Subject:" + currentIdentity.Name + "<BR/>");
    
                    foreach (Claim claim in currentIdentity.Claims)
                    {
                        writer.Write("   ClaimType: " + claim.ClaimType + "<BR/>");
                        writer.Write("   ClaimValue: " + claim.Value + "<BR/");
                        writer.Write("   ClaimValueTypes: " + claim.ValueType + "<BR/>");
                        writer.Write("   Issuer: " + claim.Issuer + "<BR/");
                        writer.Write("   OriginalIssuer: " + claim.OriginalIssuer + "<BR/>");
                        writer.Write("   Properties: " + claim.Properties.Count.ToString() + "<BR/>");
                    }
                }
                catch (Exception ex)
                {
                    writer.Write("exception occurred: " + ex.Message);
                }
    
            }
    
  2. Deploy the solution and add the Web Part to the home page of the FBA Site web application (see Figure 16).

    Figure 16. Claim type and claim value information

    Claim type and claim value information

  3. Notice the following two claims.

    ClaimType: https://schemas.microsoft.com/sharepoint/2009/08/claims/userid
    ClaimValue: 0#.f|aspnetmembership|admin1
    ClaimType: https://schemas.microsoft.com/ws/2008/06/identity/claims/role
    ClaimValue: Admin
    

    The role claim is retrieved from the ASP.NET role provider. Remember that Admin is the name of the role that we assigned to the user; the role is admin1 when we run the SQL query to add the role for the user.

Step 8: Adding More Users and Roles

Next, add additional users and roles.

To add more users and roles

  1. Run the following SQL query to add more users and roles to the provider.

    declare @now datetime
    set @now= GETDATE()
    
    exec aspnet_Membership_CreateUser 'MyAppName','bob','pass@word1',
        '','bob@contoso.com','','',1,@now,@now,0,0,null
    exec aspnet_Membership_CreateUser 'MyAppName','mary','pass@word1',
        '','mary@contoso.com','','',1,@now,@now,0,0,null
    exec aspnet_Membership_CreateUser 'MyAppName','jack','pass@word1',
    '','jack@contoso.com','','',1,@now,@now,0,0,null
    
    EXEC aspnet_Roles_CreateRole 'MyAppName', 'Employee'
    EXEC aspnet_Roles_CreateRole 'MyAppName', 'TeamManager'
    EXEC aspnet_Roles_CreateRole 'MyAppName', 'CEO'
    
    EXEC aspnet_UsersInRoles_AddUsersToRoles 'MyAppName', 'bob', 'Employee', 8 
    EXEC aspnet_UsersInRoles_AddUsersToRoles 'MyAppName', 'mary', 'TeamManager', 8 
    EXEC aspnet_UsersInRoles_AddUsersToRoles 'MyAppName', 'jack', 'CEO', 8 
    EXEC aspnet_UsersInRoles_AddUsersToRoles 'MyAppName', 'jack', 'Admin', 8 
    
  2. On the ribbon, under Site Actions, select Site Permissions, and then click Grant Permissions. Click the Browse icon to open the People Picker dialog box. Ensure that you are still logged on as admin1.

  3. Select Forms Auth, as shown in Figure 17.

    Figure 17. People Picker displaying search results

    People Picker displaying search results

  4. Type bob in the search box, as shown in Figure 17, and then click Search. One record should be returned.

  5. Double-click bob to add it to the Add-> box.

  6. Click OK.

  7. Repeat Step 4 through Step 6 to add the user mary.

  8. Select FBA Site Members from the drop-down box, as shown in Figure 18.

    Figure 18. Granting permission to users

    Granting permission to users

  9. Click OK.

  10. On the ribbon, click Grant Permissions.

  11. Click Browse to launch the People Picker.

  12. Again, select Forms Auth on the left side, as shown earlier in Figure 17.

  13. Type ceo in the search box. One record should be returned, as shown in Figure 19.

    Note

    In the example in this article, ceo is a role from the ASP.NET role provider. We added this role at the beginning of Step 8, by using a SQL query.

    Figure 19. Searching for a role named ceo

    Searching for a role named ceo

  14. Double-click ceo to add it to the Grant Permission page.

  15. Grant the role ceo full-control permission, as shown in Figure 20.

    Figure 20. Granting ceo full-control permission

    Granting ceo full-control permission

  16. Click admin1 on the top-right corner of the page, and then select Sign in as Different User, as shown in Figure 21.

    Figure 21. Signing in as a different user

    Signing in as a different user

    Try to log on the site as the user bob, and then as the user mary. Notice that the Web Part displays the correct role claim from the role provider.

  17. Try to log on as jack. Notice that the user jack gets the following two claims.

    ClaimType: https://schemas.microsoft.com/ws/2008/06/identity/claims/role

    ClaimValue: Admin

    ClaimType: https://schemas.microsoft.com/ws/2008/06/identity/claims/role

    ClaimValue: ceo

    The two claims match the roles that we assigned to it in the SQL query earlier. Remember that we granted permission to the role ceo, so as long as the user has a ceo claim, it should be able to log onto the site and also have the corresponding permission.

Conclusion

In this walkthrough, you learn how to create forms-based authentication for claims-based web applications by using ASP.NET SQL membership and role providers.

Additional Resources

For more information, see the following resources: