共用方式為


Claims Walkthrough: Creating Forms-Based Authentication for Claims-Based SharePoint 2010 Web Applications Using Custom Membership and Role Providers

Summary:  Learn how to create forms-based authentication for claims-based web applications by using a custom membership and role provider.

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 Custom Membership and Role Providers

  • Step 1: Reviewing the Membership and Role Provider Code

  • Step 2: Building and Deploying the Membership and Role Provider

  • Step 3: Creating a SharePoint Web Application

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

  • Step 5: Testing Forms-Based Authentication

  • Step 6: Viewing Claims

  • Conclusion

  • Additional Resources

Click to get code Download code: SharePoint 2010 Forms Authentication Using Custom Membership and Role Providers.zip

Overview of Authenticating Claims-Based Web Applications by Using Custom Membership and Role Providers

In this walkthrough, you create a claims-based web application by using a custom 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: Reviewing the Membership and Role Provider Code

First, review the code for the membership and role provider.

To review the membership and role provider code

  1. Open the ContosoProviders project that is included in the code sample download that accompanies this article: Download code: SharePoint 2010 Forms Authentication Using Custom Membership and Role Providers.zip.

    Note

    This project contains the definition for the membership and role providers that will be used for the claim-based web application.

  2. Open the Members.cs file.

    Note

    The membership provider is defined as ContosoProviders.Members. UserDB is a string array that simulates the user database.

    private static string[] UserDB = {
            "user1:user1@contoso.com",
            "user2:user2@contoso.com",
            "user3:user3@contoso.com",
            "user4:user4@contoso.com",
            "user5:user5@contoso.com",
            "user6:user6@contoso.com"
            };
    
  3. Review the following two methods.

    public override MembershipUser GetUser(string username, bool userIsOnline)
    public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
    

    These two methods are used to get the MembershipUser object that is based on the user name.

  4. Review the following two methods.

    public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
    public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
    

    These two methods are called by the SharePoint People Picker when the user tries to search or resolve user names.

  5. Review the ValidateUser method.

    public override bool ValidateUser(string username, string password)
    

    This method is used to validate the user's credentials. In this sample membership provider, we simply verify the existence of the user (we do not check the password).

    Note

    In a production environment, you should verify the user password. This sample is for demonstration purposes only and should not be used in a production environment.

  6. Open the Roles.cs file:

    • The role provider is defined as ContosoProviders.Roles.

    • The UserRoleDB array and the RoleDB array are used to simulate the user and role store.

    private static string[] UserRoleDB = {
            "user1:Role1:Role2:Role3",
            "user2:Role2:Role4",
            "user3:Role3:Role1:Role4",
            "user4:Role4:Role1:Role2",
            "user5:Role2:Role1",
            "user6:Role1:Role4"
            };
    
    private static string[] RoleDB = {
                    "Role1", "Role2", "Role3", "Role4"
    };
    
  7. The RoleExists (string rolename) property is used to search for or resolve role names.

    Note

    There is no wildcard support for roles.

  8. The GetRolesForUser method is called by SharePoint during the logon process, to obtain the user's claim (role) information.

Step 2: Building and Deploying the Membership and Role Provider

Next, build and deploy the membership and role provider.

To build and deploy the membership and role provider

  1. Right-click the ContosoProviders project, and then click Rebuild.

  2. Deploy the ContosoProviders.dll to the global assembly cache.

Step 3: Creating a SharePoint Web Application

Next, create the SharePoint web application.

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 Server 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 – Custom FBA.

  6. Change the Port number to 500.

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

    • Click Enable Forms Based Authentication (FBA).

    • Clear other authentication modes.

  8. In the membership provider and role manager fields, type the following names exactly as shown, all in lowercase letters:

    • ASP.NET membership provider name: custommembershipprovider

    • ASP.NET role manager name: customroleprovider

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

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

  10. Under Application Pool, select Using Existing Application Pool : SharePointAppPool.

  11. In the Database Name and Authentication section, change the database name to WSS_Content_500.

  12. Leave other settings as the defaults.

  13. Click OK to create the web application.

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

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

  • Central Administration to enable picking for site collections

  • Security Token Service to enable sign in and for issuing tokens

  • FBA Web Application to enable picking on the local web application

To configure the membership and role provide for the SharePoint web application

  1. In the web.config file for the custom FBA web application website, add the following entry inside the Providers element of the <membership> tag.

    <add name="custommembershipprovider" type="ContosoProviders.Members, ContosoProviders, Version=1.0.0.0, 
      Culture=neutral, PublicKeyToken=26fc91a86676aa9f" />
    

    After you add the value for the provider, your web.config file should resemble Figure 1.

    Figure 1. Providers value for the custom FBA web application

    Providers value for the custom FBA web application

  2. Add the following role manager element to the Providers element, under the <RoleManager> section, as shown in Figure 2.

    <add name="customroleprovider" type="ContosoProviders.Roles, 
      ContosoProviders, Version=1.0.0.0, Culture=neutral, 
      PublicKeyToken=26fc91a86676aa9f" />
    

    Figure 2. Role manager value for custom FBA web application

    Role manager value for custom FBA web application

  3. Repeat the previous steps for both the Central Administration website and the SecurityTokenServiceApplication website.

    Note

    The web.config file for the SharePoint STS website does not contain the <system.web> section. You must manually add the section. For an example of web.config files, see, Download code: ClaimsWebConfig_MSDNExample.zip, which accompanies the article Claims Walkthrough: Creating Forms-Based Authentication for Claims-Based SharePoint 2010 Web Applications Using ASP.NET SQL Membership and Role Providers.

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 custom FBA web application, http://intranet.contoso.com:500.

    Figure 3. Configuring the custom FBA web application

    Configuring the custom FBA web application

  3. Change the title to Custom FBA Site, as shown in Figure 3.

  4. In the User name field, click the Browse icon to find the user that we added previously.

  5. Select Forms Auth on the left pane, type user1 in the search box, and then click the search button, as shown in Figure 4.

    Figure 4. Searching for user1 by using the People Picker

    Searching for user1 by using the People Picker

  6. In the result area, double-click user1. This returns you to the site collection creation page.

  7. Click OK to create the site collection.

  8. Browse to http://intranet.contoso.com:500. You should see a logon page, as shown in Figure 5.

    Figure 5. Logon page

    Logon page

  9. Type user1 for the username credential, and then click Sign In. (The password can be anything that you choose.)

  10. After you log on, notice that the user name in the top-right corner appears as user1, as shown in Figure 6.

    Figure 6. User name in top-right corner

    User name in top-right corner

Step 6: Viewing Claims

Next, view the claims.

To view claims

  1. Create a Web Part. Replace the RenderContent function with the following code (also see the FBAClaimsViewer.cs. file that is included in the download that accompanies this article).

    Note

    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 website application.

  3. You should see output similar to Figure 7.

    Figure 7. Claim type and claim value information

    Claim type and claim value information

  4. Notice the following three claims:

    ClaimType: https://schemas.microsoft.com/ws/2008/06/identity/claims/role
    ClaimValue: Role1
    Issuer: SharePoint
    Properties: 0
    ClaimType: https://schemas.microsoft.com/ws/2008/06/identity/claims/role
    ClaimValue: Role2
    Issuer: SharePoint
    Properties: 0
    ClaimType: https://schemas.microsoft.com/ws/2008/06/identity/claims/role
    ClaimValue: Role3
    Issuer: SharePoint
    Properties: 0
    

    The role claim is retrieved from ContosoProviders.Roles.

  5. On the ribbon, under Site Actions, click Site Permissions, and then click Grant Permissions. Click the Browse icon to open the People Picker dialog box.

  6. Type role2, and then click Search, as shown in Figure 8.

    Figure 8. Searching for role2 in the People Picker

    Searching for role2 in the People Picker

  7. Try adding role2 to the Members group, and then check the following:

    • Who will be able to log on to the site now? Why?

    • Try to log on by using the users in role2 and see whether there is any problem.

Conclusion

Forms-based authentication provides custom identity management in Microsoft SharePoint Server 2010. In this walkthrough, you learn how to create forms-based authentication for a claims-based web application by using a custom membership and role provider.

Additional Resources

For more information, see the following resources: