Tuesday, May 8, 2012

customized Claims Provider






Overview of Creating a Claims Provider for a Trusted Login Provider
In Claims Walkthrough: Creating Trusted Login Providers (SAML Sign-in) for SharePoint 2010, we did not create a claims provider for the trusted login provider. We asked Microsoft SharePoint 2010 to generate a SPTrustedClaimProvider object for resolving, listing, and searching claims from the trusted login provider. The available claims are hard-coded when the SPTrustedLoginProvider object, for example, idClaim.AddKnownClaimValue("user1@wingtip.com"), is created and registered.
In this example, we create a custom claims provider for the WingtipSTS. This sample uses an in-memory string array to store users and claims information. A real-world implementation should consider querying a directory service to store user information in a database.
note Note:
For more information about claims providers, see Claims Provider and Claims Walkthrough: Writing Claims Providers for SharePoint 2010.

By default, SharePoint 2010 does not offer search and resolve in People Picker for trusted login providers. Therefore, anything that the user types in the People Picker, the People Picker returns as it was typed. This can create problems, for example, if access is added for a user but the user still does not have access. But, as of today, there is no industry standard or protocol that enables search and resolve. Even if there was a standard or protocol, in some scenarios, this functionality may not be available. For example, Windows Live ID has scenarios where search is not allowed for privacy reasons.
The solution to this problem is a custom claims provider. A custom claims provider can implement a specific protocol to enable search and resolve (if available) or can just perform basic validation on what the user typed to prevent errors. For example, if the trusted login provider is for granting Contoso users access to the Fabrikam company website, but Contoso does not have a protocol or service that can be used for search and resolve, then the custom claims provider can be used to validate, for example, that email addresses always have the postfix "@contoso.com".
Notice that during registration, the name of the claims provider must match the name of the trusted login provider. The reason for this is that the issuer value for claims that come from the trusted login provider is the name of that trusted login provider. During picking, if the custom claims provider has a different name, then the claims added by that claims provider via the People Picker will have a different "issuer" value. Therefore, during authorization there will be a mismatch. For more information, see Replacing the Out of Box Name Resolution in SharePoint 2010—Part 2.
Changing the assigned claims provider for the trusted login provider is important because, otherwise, the default claims provider will be used in addition to the custom claims provider, which can cause confusion. For more information about changing the assigned claims provider for the trusted login provider, see How to Override the Default Name Resolution and Claims Provide in SharePoint 2010.
This article and walkthrough example targets solving the issue about search and resolution for trusted login providers. In addition, a user may also add a custom claims provider for augmentation, which is not shown in this article. Having a claims provider to solve search and resolve for this case and a second claims provider for claims augmentation (in a CRM scenario) is a valid configuration.
note Note:
A trusted login provider is an external (that is, external to SharePoint) security token service (STS) that SharePoint trusts. For information about claims terms definitions, see Claims-Based Identity Term Definitions.

SAML passive sign-in describes the process of signing in. When a sign-in for a web application is configured to accept tokens from a trusted login provider, this type of sign-in is called SAML passive sign-in. For more information, see Incoming Claims: Signing into SharePoint.

Step 1: Creating the Claims Provider Project

  1. Open the TrustedLogin solution download code that accompanies this article. It should contain three projects, as shown in Figure 1:

    • TestRPWeb website
    • WingtipSTS website
    • RegisterSTS WinForm application



      Figure 1. Three projects included in the TrustedLogin solution

      Three projects included in TrustedLogin solution
  2. In Solution Explorer, right-click the TrustedLogin solution, select Add, and then click New Project.
  3. Under Visual C#, select the Empty SharePoint Project template, select SharePoint, and then click 2010. Name the SharePoint project WingtipClaimProvider. Then, do the following:

    • In the customization wizard, select Farm Solution.
    • Type https://intranet.contoso.com as the site for debugging.
  4. In the WingtipClaimProvider project, add a reference to Microsoft.IdentityModel.dll.

    For more information about Microsoft.IdentityModel.dll, see Windows Identity Foundation.
  5. Right-click the WingtipClaimProvider project, select Add, and then click New Item.
  6. Add a new class file to the project, named WingtipClaimTypes.cs.
  7. The WingtipClaimTypes.cs file defines the claim types that are supported by this claims provider. Replace the code in the WingtipClaimTypes.cs file with the following code. Notice that we added one additional claim type: department.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace WingtipClaimProvider
    {
        public class WingtipClaimType
        {
            public static string EmailAddress = 
            "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress";
            public static string Title = 
            "http://schemas.wingtip.com/sharepoint/2009/08/claims/title";
            public static string Department = 
            "http://schemas.wingtip.com/sharepoint/2009/08/claims/department";
        }
    }
    
    

Step 2: Creating the WingtipUserInfo Class That Stores User Information and Can Be Used to Query User Claims

  1. In the project, add a new class file named WingtipUserInfo.cs, as shown in Figure 2.



    Figure 2. Adding a new class file to the WingtipClaimProvider project

    Adding a new class file to WingtipClaimProvider
  2. Replace the using statement with the following code.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.SharePoint.Administration;
    using Microsoft.IdentityModel.Claims;
    using System.Collections;
    
    
  3. Add the following two string arrays to the WingtipUserInfo class. These two string arrays serve as the user information store.

    • The userDB string array contains the user information and associated claims. (Email address is used as the identifier of the user.)
    • The claimsDB string array contains the available claims that can be searched by this claims provider.
            private static string[] userDB = 
               {
                "user1@wingtip.com:Email:user1@wingtip.com", 
                "user2@wingtip.com:Email:user1@wingtip.com", 
                "user3@wingtip.com:Email:user1@wingtip.com", 
                "user1@wingtip.com:Title:Engineer", 
                "user2@wingtip.com:Title:Manager", 
                "user3@wingtip.com:Title:CEO", 
                "user1@wingtip.com:Department:Finance", 
                "user2@wingtip.com:Department:IT", 
                "user3@wingtip.com:Department:AP", 
               };
    
            private static string[] claimsDB = 
               {
                "Email:user1@wingtip.com", 
                "Email:user2@wingtip.com",
                "Email:user3@wingtip.com",
                "Title:Employoee",
                "Title:Manager",
                "Title:NorthWest",
                "Department:Finance",
                "Department:IT",
                "Department:AP"
               };
    
  4. Add the following code to the WingtipUserInfo class. These functions are just utility functions that read and parse information from userDB and claimsDB. They are used for resolving, searching, and listing claims.

            /// <summary>
            /// A real-world implementation should look up a directory service 
            /// or database to retrieve a user claim.
            /// The following code is used only for demonstration purposes.
            /// </summary>
            /// <param name="username"></param>
            /// <returns></returns>
            public static List<Claim> GetClaimsForUser(string username)
            {
                 List<Claim> userClaims = new List<Claim>();
                foreach(string userInfo in userDB)
                {
                    string[] claims = userInfo.Split(new string[] { ":" }, 
                    StringSplitOptions.RemoveEmptyEntries);
                    if (username == claims[0])
                    {
                        userClaims.Add(new Claim(GetClaimTypeForRole(claims[1]), 
                        claims[2], Microsoft.IdentityModel.Claims.ClaimValueTypes.String));
                    }
                }
    
                return userClaims;
            }
    
    
            // Manually construct a list of users. 
            // In a real-world production environment,
            // you should look up from a directory service or database to 
            // retrieve the user information.
            public static List<string> GetAllUsers()
            {
                List<string> allUsers = new List<string>();
    
                // Adding forms-based users.
                allUsers.Add("user1@wingtip.com");
                allUsers.Add("user2@wingtip.com");
                allUsers.Add("user3@wingtip.com");
    
                // Adding Windows domain users, if you want this provider to 
                // support Windows claims mode.
                return allUsers;
            }
    
            /// <summary>
            /// This function returns all the known claims from the CRM system 
            /// so that the claims provider is able to
            /// search and resolve the claims in the People Picker.
            /// </summary>
            /// <returns></returns>
            public static Hashtable GetAllClaims()
            {
                Hashtable knownClaims = new Hashtable();
                foreach(string claimItem in claimsDB)
                {
                    string[] claim = claimItem.Split(new string[] { ":" }, 
                    StringSplitOptions.RemoveEmptyEntries);
                    knownClaims.Add(claim[1].ToLower(), claim[0].ToLower());
                }
                return knownClaims;
            }
    
    
            public static string GetClaimTypeForRole(string roleName)
            {
                if (roleName.Equals("Email", StringComparison.OrdinalIgnoreCase))
                    return WingtipClaimType.EmailAddress;
                else if (roleName.Equals("Title", StringComparison.OrdinalIgnoreCase))
                    return WingtipClaimType.Title;
                else if (roleName.Equals("Department", 
                StringComparison.OrdinalIgnoreCase))
                    return WingtipClaimType.Department;
                else
                    throw new Exception("Claim Type not found!");
            }
    
    

Step 3: Adding Code for Claims Augmentation

  1. Add a new class file named ClaimProvider.cs.
  2. Replace the using statements with the following code.

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.SharePoint.Administration.Claims;
    using Microsoft.SharePoint.Administration.Claims;
    using Microsoft.SharePoint.WebControls;
    using Microsoft.IdentityModel.Claims;
    
    
  3. Change the class inheritance to match the following code.

        class ClaimProvider: SPClaimProvider
    
    
  4. Add a constructor and two properties.

            public ClaimProvider(string displayName)
                : base(displayName)
            {
            }
    
            public override string Name
            {
                get { return "WingtipClaimProvider"; }
            }
    
            // The AssociatedTrustedLoginProviderName property is used for 
            // generating the SPClaim object. 
            public string AssociatedTrustedLoginProviderName
            {
                get { return "WingtipSTS";  }
            }
    
    
  5. Add support for claims augmentation, search, and resolve.

          /// <summary>
            /// Must return true if you are doing claims augmentation.
            /// </summary>
            public override bool SupportsEntityInformation
            {
                get { return true; }
            }
    
            /// <summary>
            /// Return true if you support claims resolve in the People Picker.
            /// </summary>
            public override bool SupportsResolve
            {
                get { return true; }
            }
    
            /// <summary>
            /// Return true if you support claims search in the People Picker.
            /// </summary>
            public override bool SupportsSearch
            {
                get { return true; }
            }
    
            /// <summary>
            /// Return true if you support hierarchy display in the People Picker.
            /// </summary>
            public override bool SupportsHierarchy
            {
                get { return false; }
            }
    
            public override bool SupportsUserSpecificHierarchy
            {
                get
                {
                    return base.SupportsUserSpecificHierarchy;
                }
            }
    
    
  6. Add the following function to provide the Claim Types information.

    Notice that in FillEntityTypes, we support both User and FormRoles. You must return the entity type for each of the claim types that you support. In this case, EmailAddress is treated as an identity claim (SPClaimEntityTypes.User), and the other two claim types are treated as roles (SPClaimEntityTypes.FormRole).

            /// <summary>
            /// Returns all the claims types that are supported by this provider.
            /// </summary>
            /// <param name="claimTypes"></param>
            protected override void FillClaimTypes(List<string> claimTypes)
            {
                if (null == claimTypes)
                {
                    throw new ArgumentNullException("claimTypes");
                }
    
                // Add the claim types that will be added by this claims provider.  
                claimTypes.Add(WingtipClaimType.EmailAddress);
                claimTypes.Add(WingtipClaimType.Title);
                claimTypes.Add(WingtipClaimType.Department);
            }
    
            /// <summary>
            /// Return all claim value types that correspond to the claim types.
            /// You must return the values in the same order as 
            /// in FillClaimTypes(). 
            /// </summary>
            /// <param name="claimValueTypes"></param>
            protected override void FillClaimValueTypes(List<string> claimValueTypes)
            {
    
                if (null == claimValueTypes)
                {
                    throw new ArgumentNullException("claimValueTypes");
                }
    
                claimValueTypes.Add
                (Microsoft.IdentityModel.Claims.ClaimValueTypes.String);
                claimValueTypes.Add
                (Microsoft.IdentityModel.Claims.ClaimValueTypes.String);
                claimValueTypes.Add
                (Microsoft.IdentityModel.Claims.ClaimValueTypes.String);
            }
    
            /// <summary>
            /// Required for the People Picker.
            /// Tells the People Picker what information is available
            /// for the entity.
            /// </summary>
            /// <param name="schema"></param>
            protected override void FillSchema(SPProviderSchema schema)
            {
                schema.AddSchemaElement(new SPSchemaElement
                (PeopleEditorEntityDataKeys.DisplayName,
                              "DisplayName",
                              SPSchemaElementType.TableViewOnly));
            }
    
            /// <summary>
            /// Returns the entity type for the claims that are returned from the 
            /// claims provider.
            /// </summary>
            /// <param name="entityTypes"></param>
            protected override void FillEntityTypes(List<string> entityTypes)
            {
                entityTypes.Add(SPClaimEntityTypes.User);
                entityTypes.Add(SPClaimEntityTypes.FormsRole);
                entityTypes.Add(SPClaimEntityTypes.FormsRole);
            }
    
    
  7. Add the following utility function, which is used to generate the claim object.

    noteNote:
    We explicitly specify that the issuer of the claim is WingtipSTS (not WingtipClaimProvider).
            // The claim from this provider should have WingtipSTS as the 
            // provider name.
            private SPClaim CreateClaimForSTS(string claimtype, string claimValue)
            {
    
                SPClaim result = new SPClaim(claimtype,
                                            claimValue, 
                      Microsoft.IdentityModel.Claims.ClaimValueTypes.String, 
                      SPOriginalIssuers.Format
                                      (SPOriginalIssuerType.TrustedProvider, 
                                       AssociatedTrustedLoginProviderName));
    
                return result;
            }
    
    
  8. Add the FillClaimsForEntity function to support claims augmentation.

          /// <summary>
            /// Implement this method if the provider supports claims augmentation.
            /// </summary>
            /// <param name="context"></param>
            /// <param name="entity"></param>
            /// <param name="claims"></param>
            protected override void FillClaimsForEntity(Uri context, 
            SPClaim entity, List<SPClaim> claims)
            {
                if (null == entity)
                {
                    throw new ArgumentNullException("entity");
                }
                if (null == claims)
                {
                    throw new ArgumentNullException("claims");
                }
    
                //Adding the role claim.
                SPClaim userIdClaim = 
                SPClaimProviderManager.DecodeUserIdentifierClaim(entity);
    
                //Adding claims for users.
                List<string> allWingtipUsers = WingtipUserInfo.GetAllUsers();
    
                if (allWingtipUsers.Contains(userIdClaim.Value.ToLower()))
                {
                    List<Claim> userClaims = 
                    WingtipUserInfo.GetClaimsForUser
                    (userIdClaim.Value.ToLower());
                    foreach (Claim claim in userClaims)
                    {
                        claims.Add(CreateClaimForSTS(claim.ClaimType, claim.Value));
                    }
    
                }
    
            }
    
    

Step 4: Adding Code for Searching Claims

  1. Add the FillSearch method to support searching claims.

    Notice the highlighted part of the function. When a user searches for email address, we return the identity claim; otherwise, we return the role claim.

    noteNote:
    We use LINQ query to support wildcard search in this case.
           /// <summary>
            /// Required if you implement the claims search for People Picker.
            /// </summary>
            /// <param name="context"></param>
            /// <param name="entityTypes"></param>
            /// <param name="searchPattern"></param>
            /// <param name="hierarchyNodeID"></param>
            /// <param name="maxCount"></param>
            /// <param name="searchTree"></param>
            protected override void FillSearch(Uri context, string[] entityTypes, 
            string searchPattern, string hierarchyNodeID, int maxCount, 
            SPProviderHierarchyTree searchTree)
            {
                string keyword = searchPattern.ToLower();
                Hashtable knownClaims = WingtipUserInfo.GetAllClaims();
                List<string> knownClaimsList = new List<string>();
    
                //Convert the knownClaims.Key into a List<string> for LINQ query.
                foreach (string claim in knownClaims.Keys)
                {
                    knownClaimsList.Add(claim);
                }
    
    
                var claimQuery = knownClaimsList.Where(claim => 
                claim.IndexOf(keyword) >= 0).Select(claim => claim);
    
                foreach (string claimValue in claimQuery)
                {
                    //Get the ClaimType for the claim type.
                    //For example, if you search for "SalesManager", 
                    //the ClaimType will be CRMClaimType.Role.
    
                    string claimType = WingtipUserInfo.GetClaimTypeForRole((string)
                    knownClaims[claimValue]);
    
                    PickerEntity entity = CreatePickerEntity();
                    entity.Claim = CreateClaimForSTS(claimType, claimValue);
                    entity.Description = claimValue;
                    entity.DisplayText = claimValue;
                    entity.EntityData[PeopleEditorEntityDataKeys.DisplayName] = 
                    claimValue;
    
                    if (string.Compare(claimType, WingtipClaimType.EmailAddress, 
                    true) == 0)
                    {
                        entity.EntityType = SPClaimEntityTypes.User;
                    }
                    else
                    {
                        entity.EntityType = SPClaimEntityTypes.FormsRole;
                    }
    
    
                    entity.IsResolved = true;
                    searchTree.AddEntity(entity);
                }
    
            }
    
    

Step 5: Adding Code for Claims Resolution

  1. Add the two FillResolve methods to support resolving claims.

    The code tries to match the keyword with the values in ClaimsDB, and then returns the appropriate data.

          /// <summary>
            /// Resolve one single claim by using exact match. 
            /// This method is required for both claims search
            /// and claims resolve.
            /// </summary>
            /// <param name="context"></param>
            /// <param name="entityTypes"></param>
            /// <param name="resolveInput"></param>
            /// <param name="resolved"></param>
            protected override void FillResolve(Uri context, string[] entityTypes, 
            SPClaim resolveInput, List<PickerEntity> resolved)
            {
                string keyword = resolveInput.Value.ToLower();
                Hashtable knownClaims = WingtipUserInfo.GetAllClaims();
    
                if (knownClaims.ContainsKey(keyword))
                {
                    // Get the claim type.
                    // For example, if you search for "SalesManager", the ClaimType 
                    // will be CRMClaimType.Role.
                    // In this case, the keyword is the value of the claim.
                    string claimValue = keyword;
                    string claimType = 
                    WingtipUserInfo.GetClaimTypeForRole((string)knownClaims[keyword]);
    
                    PickerEntity entity = CreatePickerEntity();
                    entity.Claim = CreateClaimForSTS(claimType, claimValue);
                    entity.Description = claimValue;
                    entity.DisplayText = claimValue;
                    entity.EntityData[PeopleEditorEntityDataKeys.DisplayName] = 
                    claimValue;
                    if (string.Compare(claimType, WingtipClaimType.EmailAddress, true) 
                    == 0)
                    {
                        entity.EntityType = SPClaimEntityTypes.User;
                    }
                    else
                    {
                        entity.EntityType = SPClaimEntityTypes.FormsRole;
                    }
    
                    entity.IsResolved = true;
                    resolved.Add(entity);
                }
            }
    
    
            /// <summary>
            /// Required if you implement claims resolve for the People Picker.
            /// </summary>
            /// <param name="context"></param>
            /// <param name="entityTypes"></param>
            /// <param name="resolveInput"></param>
            /// <param name="resolved"></param>
            protected override void FillResolve(Uri context, string[] entityTypes, string 
            resolveInput, List<PickerEntity> resolved)
            {
    
                string keyword = resolveInput.ToLower();
                Hashtable knownClaims = WingtipUserInfo.GetAllClaims();
                List<string> knownClaimsList = new List<string>();
    
                // Convert the knownClaims.Key into a List<string> for LINQ query.
                foreach (string claim in knownClaims.Keys)
                {
                    knownClaimsList.Add(claim);
                }
    
                var claimQuery = knownClaimsList.Where(claim => 
                claim.IndexOf(keyword) >= 0).Select(claim => claim);
    
                foreach (string claimValue in claimQuery)
                {
                    // Get the claim type.
                    // For example, if you search for "SalesManager", 
                    // the ClaimType will be CRMClaimType.Role.
    
                    string claimType = WingtipUserInfo.GetClaimTypeForRole((string)
                    knownClaims[claimValue]);
    
                    PickerEntity entity = CreatePickerEntity();
                    entity.Claim = CreateClaimForSTS(claimType, claimValue);
                    entity.Description = claimValue;
                    entity.DisplayText = claimValue;
                    entity.EntityData[PeopleEditorEntityDataKeys.DisplayName] = claimValue;
                    if (string.Compare(claimType, WingtipClaimType.EmailAddress, 
                    true) == 0)
                    {
                        entity.EntityType = SPClaimEntityTypes.User;
                    }
                    else
                    {
                        entity.EntityType = SPClaimEntityTypes.FormsRole;
                    }
                    entity.IsResolved = true;
                    resolved.Add(entity);
                }
    
            }
    
    
  2. Add the following FillHierarchy method showing that we are not supporting hierarchy.

           protected override void FillHierarchy(Uri context, string[] entityTypes, 
                string hierarchyNodeID, int numberOfLevels, SPProviderHierarchyTree hierarchy)
            {
                throw new NotImplementedException();
            }
    
    
  3. Compile the project and correct any errors.

Step 6: Registering the WingtipClaimProvider with WingipSTS

During registration, the name of the claims provider must match the name of the trusted login provider. The reason for this is that the issuer value for claims that come from the trusted login provider will be the name of that trusted login provider. During picking, if the custom claims provider has a different name, then the claims added by that claims provider via the People Picker will have a different issuer value. Therefore, during authorization there will be a mismatch. For more information, see Replacing the Out of Box Name Resolution in SharePoint 2010—Part 2.
  1. In Solution Explorer, right-click the Features node, and then click Add a New Feature.
  2. Change the Scope of the feature to Farm.
  3. Right-click Feature1, and then click Add an Event Receiver.
  4. Replace the using statement with the following code.

    using System;
    using System.Runtime.InteropServices;
    using System.Security.Permissions;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Security;
    using Microsoft.SharePoint.Administration.Claims;
    
    
  5. Change the class inheritance to match the following code.

    public class Feature1EventReceiver :SPClaimProviderFeatureReceiver
    
    
  6. Add the following code into the class. Leave the other code commented.

            private string providerDisplayName = "Wingtip Claim Provider";
            private string providerDescription = "Provides Claims from Wingtip";
    
            public override string ClaimProviderAssembly
            {
                get { return typeof
                (WingtipClaimProvider.ClaimProvider).Assembly.FullName; }
            }
    
    
            public override string ClaimProviderDisplayName
            {
                get
                {
                    return providerDisplayName;
                }
            }
    
            public override string ClaimProviderType
            {
                get { return typeof(WingtipClaimProvider.ClaimProvider).FullName; }
            }
    
            public override string ClaimProviderDescription
            {
                get { return providerDescription; }
            }
    
            public override bool ClaimProviderUsedByDefault
            {
                get
                {
                    return true;
                }
            }
    
    
  7. Compile the WingtipClaimProvider project and ensure that it builds successfully.
  8. Right-click the WingtipClaimProvider project, and then click Deploy. This step registers the claims provider with the farm.
  9. Open Form1 in the RegisterSTS project.
  10. Add a button named Update ClaimProvider.

    You should have only two buttons on the form: One is register WingtipSTS and the other is Update ClaimProvider, as shown in Figure 3.



    Figure 3. Form1 showing the Update ClaimProvider button

    Form1 showing the Update ClaimProvider button
  11. In the code-behind of the new button, add the following code.

                SPSecurityTokenServiceManager manager = SPSecurityTokenServiceManager.Local;
    
                string providerName = "WingtipSTS";
    
                SPTrustedLoginProvider provider = manager.TrustedLoginProviders[providerName];
                provider.ClaimProviderName = "WingtipClaimProvider";
                provider.Update();
            }
    
  12. Compile the application and correct any errors.
  13. Right-click the RegisterSTS project, select Debug, and then Start New Instance.
  14. When the application starts, click the Update ClaimProvider button. This updates the claims provider for the WingtipSTS trusted login provider.

Step 7: Test the Claims Provider

Again, ensure that your WingtipSTS project is running and can be accessed via browser.
  1. Launch the Central Administration website.
  2. On the Create Site Collection page (see Figure 4), select https://intranet.contoso.com.



    Figure 4. Create Site Collection page

    Create Site Collection page
  3. In the Site Collection Administrator section, click the Browse icon to launch the People Picker. Notice that you have a "Wingtip Claim Provider" on the left side, as shown in Figure 5. This is the claims provider that you just created.



    Figure 5. The Wingtip Claim Provider as displayed in the People Picker

    Wingtip Claim Provider displayed in People Picker
  4. In the left pane, select Wingtip Claim Provider. Type user in the Search box. Three users should be returned, as shown in Figure 6.



    Figure 6. Searching for "user" returns three users in the People Picker

    Searching for "user" returns three users
  5. Select User1@wingtip.com as the site collection administrator.
  6. Create the site collection under https://intranet.contoso.com/sites/Test1.
  7. After the site collection is created, in your browser, navigate to https://intranet.contoso.com/sites/Test1.
  8. On the WingtipSTS logon page, type in the credential for user1@wingtip.com (the password can be anything), as shown in Figure 7.

    noteNote:
    Ensure that you have WingtipSTS running. If not, right-click the WingtipSTS project, and then select View in Browser.


    Figure 7. The WingtipSTS logon page

    WingtipSTS logon page
  9. Click Submit. You should be redirected back to the SharePoint site. (The first launch might take several moments.)



    Figure 8. Redirected to SharePoint site after successfully logging on

    Redirected to SharePoint site after logging on
  10. On the Site Action menu, select Site Permissions.
  11. On the ribbon, click Grant Permission.
  12. Type IT, and then press Enter. After the name resolves, click IT, and then select it [Wingtip Claim Provider], as shown in Figure 9.



    Figure 9. Selecting "it [Wingtip Claim Provider]"

    Selecting "it [Wingtip Claim Provider]"
  13. Click the Browse icon to open the People Picker dialog box.
  14. Search for AP. Pick the entry that is returned from Wingtip Claim Provider, as shown in Figure 10.



    Figure 10. Selecting "AP" from Wingtip Claim Provider

    Selecting "AP" from Wingtip Claim Provider
  15. Add IT and AP to the Members group (Contributor), as shown in Figure 11.



    Figure 11. Adding "IT" and "AP" to the Members group (Contributor)

    Adding "IT" and "AP" to Members group
  16. Sign out for user1@wingtip.com, as shown in Figure 12, and then close all instances of your browser.

    noteNote:
    This step is important. Ensure that you close all instances of your browser.


    Figure 12. Signing out

    Signing out
  17. Open a new instance of Internet Explorer or another browser, and go to https://intranet.contoso.com/sites/Test1.
  18. Try to log on by using user2@wingtip.com.
  19. Can you log on? Why or why not?
  20. Try to log on by using user3@wingtip.com.
  21. Can you log on? Why or why not?
  22. Create a claim viewer Web Part, and then add it to the home page and display the claims for all three users. (The code for this step is not provided.)

Conclusion

In this walkthrough, you learn how to create a claims provider for a trusted login provider. A trusted login provider is an external STS that SharePoint trusts.

Additional Resources

For more information, see the following resources:

Change History

 

Date Description Reason
October 2010 Initial publication
Did you find this helpful?
Community Content Add
Annotations FAQ

re: bad download link Edit
The reference to code download on this posting is wrong. But, the correct code could be download from here:
 http://msdn.microsoft.com/en-us/library/ff955607.aspx

Although the posting in the above link is referring to some student labs stuff and certificates which are missing. This makes it impossible to follow the walkthrough steps.... pretty annoying!?


Sample Code Gone and Needed Edit
Reference to sample code links to a BCS project on MSDN.


Download link Bad Edit
The download link re-directs to a BCS example, not the code related to the article

Monday, May 7, 2012

cutomized claim providers


Creating Custom Claims Providers in SharePoint 2010

SharePoint 2010
Published: February 2011
Summary: Support for claims-based security in Microsoft SharePoint 2010 enables SharePoint developers to create custom claims providers for use to add custom claims to the security token of the current user. Site administrators can also see and use these custom claims when they configure permissions on securable objects such as sites, lists, items, and documents. Use the sample application associated with this article to learn how to create a custom claims provider by using the SharePoint development tools in Microsoft Visual Studio 2010 that issues custom claims based on whether the current user is a member of an Audience created by using the User Profile web service of SharePoint 2010.
Applies to:  Microsoft SharePoint Foundation | Microsoft SharePoint Server 2010 | Microsoft Visual Studio 2010 | SharePoint development tools in Microsoft Visual Studio 2010
Provided by:  Ted Pattison, Critical Path Training, LLC1 (SharePoint MVP) | Scot Hillier, Critical Path Training, LLC1 (SharePoint MVP)
Content
Click to get code2 Download the code: MSDN Claim Provider Sample (from Critical Path Training)2

Introduction to Creating Custom Claims Providers in SharePoint 2010

Microsoft SharePoint 2010 introduces a new claims-based security model in Microsoft SharePoint Foundation 2010. The support for claims-based security is scoped to the level of the web application. Whenever you create a SharePoint web application, you must decide whether the new web application will run under Claims Mode or under the older SharePoint 2007 mode known as Classic Mode. When a web application that runs in Claims Mode authenticates a user, it creates a security token for the user by using Security Assertion Markup Language (SAML). For example, if the user is authenticated by using Windows Authentication against an Active Directory account, the SAML token will contain the security identifier (ID) for the user's Active Directory account and the security ID for all the Active Directory groups that the user is in.
What is powerful about creating a custom claims provider is that your code is called each time the hosting web application authenticates the user and creates a SAML token. Your code is then given the opportunity to do the following:
  • Determine who the user is
  • Query for information about the user
  • Add claims about the user into the resulting SAML token
You can create two main types of claims providers: people picker claims provider and claims augmentation provider.
You can use the first type, a people picker claims provider, to enable a user to search and resolve entities in the standard people editor controls provided by SharePoint Foundation. These types of claims providers are used in scenarios where the authentication provider is SAML-based, and rich search and resolve experience is needed. For example, some of the SAML-based authentication providers that are included with SharePoint Foundation, such as the one used in forms-based authentication, do not offer rich search and resolve functionality. You can develop a people picker claims provider to offer a better search and resolve experience in sites that use forms-based authentication.
The second type of claims provider is a claims augmentation provider, which is used to augment the claims (such as attributes) of a user. For example, a claims augmentation provider can add custom claims to a user's security token, which provides more flexibility when you configure permissions on sites, lists, items, and documents. When the custom claims you create must be exposed in a people picker (search and resolve), this type of claims provider should also implement this aspect of the claims provider interface, as shown in the following Custom Claims Provider Walkthrough: AudienceClaimProvider and in the Visual Studio 2010 sample project (MSDN Claim Provider Sample (from Critical Path Training)2) that accompanies this article.
The sample Visual Studio 2010 project is a SharePoint project named WingtipClaimProviders. This project contains a claims augmentation provider named AudienceClaimProvider, which is built on top of the Audience feature that is supplied by the User Profile web service in SharePoint Server 2010. When a user is authenticated against a web application that is running in Claims Mode, the AudienceClaimProvider claims augmentation provider checks whether the current user is a member of any audiences. For each audience that the user is in, AudienceClaimProvider adds a claim to the user's SAML token to indicate that the user is a member of that audience.
A claims provider has another important job along with adding claims to a user's SAML token during authentication. A claims provider must also implement several different methods to interact with the People Picker page that is provided by SharePoint Foundation. A custom claims provider supplies an important point of interaction for SharePoint site administrators who are configuring permissions on lists and sites.
The idea of a custom claims provider represents a paradigm shift in the configuration of security permissions. For example, a site collection owner is no longer confined to configuring permissions solely in terms of users and groups. Now a site collection owner can configure security permissions in terms of new abstractions. You could create a claims provider that can query a back-end system for the user's birth date and make the claim as to whether this user is over 21 years old. Another claims provider could look up information about a user and make a claim about whether the user is a naturalized citizen of a particular country, such as the United States. In this sample, the claims provider creates claims that verify that the current user is a member of one or more audiences. As you will see, the presence of these claims in SAML tokens is what makes it possible to configure site and list permissions in terms of audiences, which is something that was not possible in SharePoint Server 2007 and Windows SharePoint Services 3.0.
This article walks you through the process of deploying and testing the AudienceClaimProvider claims augmentation provider. The walkthrough assumes the following:
  • You have installed SharePoint 2010.
  • You have correctly configured the User Profile web service and created some audiences.
To properly test AudienceClaimProvider, you must be running under the context of a user who is in one or more audiences. You must also test the sample in a SharePoint site that runs inside a web application that is running in Claims Mode, not in Classic Mode.

Installing and Testing the AudienceClaimProvider Claims Augmentation Provider

Installation of the sample claims provider is fairly straightforward, as described in the following steps.
  1. Ensure that you have created a few audiences and that you are logged on as a user in at least one audience.
  2. In Visual Studio 2010, open the WingtipClaimProviders.sln project.
  3. In the Properties sheet for the project, modify the Site URL property to point to a test site in your local farm. Ensure that this test site is running in a web application that was created in Claims Mode.
  4. In Solution Explorer, right-click the WingtipClaimProviders project node, and then click Deploy.

    This action deploys the project's solution package, which will install WingtipClaimProviders.dll in the global assembly cache and install a farm-level feature that registers the claims provider in the current farm. For testing purposes, the solution package also deploys an application page named ClaimsViewer.aspx and a site-level feature that adds a menu item to the Site Actions menu. This enables you to navigate to ClaimsViewer.aspx, so that you can see the claims that are added to the current user's SAML token.
  5. Run an iisreset operation.
  6. Navigate to the test site in the browser.
  7. On the Site Actions menu, click Wingtip Claims Viewer. A page opens that displays all the claims in the SAML token for the current user. You should be able to verify that there is a claim for each audience of which the current user is a member.



    Figure 1. SAML token for current user

    SAML token for current user
  8. On the Site Actions menu, click Site Permissions.
  9. On the ribbon on the Site Permissions page, click the Grant Permission button. This action displays the Grant Permission page, which enables you to configure permissions in terms of users and groups. This page also enables you to configure permissions in terms of claims. Notice the two small buttons under the input control for Users/Groups. The button with the person and the check mark is the Check User button, which enables you to resolve a user, group, or claims from text that you have typed. The button with the open book is the Browse button, which displays the People Picker page.



    Figure 2. Grant Permissions page

    Grant Permissions page
  10. Click the Browse button on the Grant Permissions page to open the People Picker page. When the People Picker page opens, type the name of an audience in the Find text box, and then click the search button to the right. Ensure that your search text matches an audience in your farm. The search should find one or more audiences and display them in the column on the right. Select an audience, and then click Add at the bottom of the page. The audience should then appear with an underlined format in the text box to the right. Click OK to close the People Picker page and return to the Grant Permissions page.



    Figure 3. People Picker page

    People Picker page
  11. On the Grant Permissions page, you should see the audience in an underlined format in the Users/Groups box. Select a permission to grant to the audience, and then click OK.
At this point, you have configured permissions so that they are granted to any user who is a member of the audience you selected. From this example, you can see that you can now use audiences as first-class security principals when you are configuring permissions on sites, lists, items, and documents.

Custom Claims Provider Walkthrough: AudienceClaimProvider

The SharePoint project that is associated with this article is named WingtipClaimProviders.sln. It contains a class named AudienceClaimProvider that demonstrates how to create a custom claims provider, and a farm-level feature named AudienceClaimProviderRegistration that is used to register and unregister the claims provider in the local SharePoint farm. The project also contains an application page named ClaimsViewer.aspx, and a feature named MainSite that adds a Site Actions menu item to navigate to this application page. When you are creating a custom claims provider, the application page and feature are not required, but they are included so that you can see all the claims for the current user when you are testing the behavior of the code.


Figure 4. WingtipClaimProviders.sln in Solution Explorer

WingtipClaimProviders.sln in Solution Explorer The first thing to do when you create a custom claims provider is to create a new class that inherits from SPClaimProvider. You must also add a public constructor that takes a single string parameter and passes it to the base class constructor, as shown in the following code.
C#
namespace WingtipClaimProviders {
  class AudienceClaimProvider : SPClaimProvider {
    public AudienceClaimProvider(string displayName)
      : base(displayName) {
    }
  }
}

When creating a custom claims provider, you typically must define one or more claim types. A claim type is identified by a unique string, and by convention it is formatted as a URI that identifies the company that created it. Each claim type must also define a type for its underlying value, which can be defined in terms of the ClaimValueTypes enumeration, as shown in the following code.
C#
// This is the only claim type supported by this provider.
protected const string AudienceClaimType = "http://www.wingtip.com/identity/claims/audience";
protected const string StringTypeClaim = Microsoft.IdentityModel.Claims.ClaimValueTypes.String;

A claims provider requires a name and a description for registration. The AudienceClaimProvider provides these values using constant fields, as shown in the following code.
C#
internal const string ClaimProviderDisplayName = "Audience Claim Provider";
internal const string ClaimProviderDescription = "SharePoint 2010 Demoware from Critical Path Training";

When you create a custom claims provider by inheriting SPClaimProvider, there are several methods and properties that you must override. For example, each claims provider must implement the read-only Name property, as shown in the following code.
C#
public override string Name {
  get { return ClaimProviderDisplayName; }
}

You must override four methods that return Boolean values to indicate the functionality that the claims provider is able to support. The AudienceClaimProvider claims augmentation provider returns true for each of these methods, as shown in the following code.
C#
public override bool SupportsEntityInformation {
  get { return true; }
}
public override bool SupportsHierarchy {
  get { return true; }
}
public override bool SupportsSearch {
  get { return true; }
}
public override bool SupportsResolve {
  get { return true; }
}

Now we will walk through each of the remaining overridable methods, which will bring the claims provider to life. We will start with two methods named FillClaimTypes and FillClaimValueTypes. Both methods pass a List of strings as an incoming parameter, and expect you to add one or more strings to this list. The FillClaimTypes method is implemented by adding the string that identifies the custom claim type. The FillClaimValueTypes method is implemented by adding the string that indicates that the custom claim type has a string-based value, as shown in the following code.
C#
protected override void FillClaimTypes(List<string> claimTypes) {
  if (claimTypes == null) throw new ArgumentException("claimTypes");
  claimTypes.Add(AudienceClaimType);
}
protected override void FillClaimValueTypes(List<string> claimValueTypes) {
  if (claimValueTypes == null) throw new ArgumentException("claimValueTypes");
  claimValueTypes.Add(StringTypeClaim);
}

The next method to implement is FillEntityTypes. Like the previous two methods, this method passes you a List of strings to which you can add one or more strings. AudienceClaimProvider implements this method by adding a single string to indicate that our claims provider creates claims based on form roles, as opposed to a claim that might identify a user or a Windows group, as shown in the following code.
C#
protected override void FillClaimsForEntity(System.Uri context, SPClaim entity, List<SPClaim> claims) {
  claims.Add(CreateClaim(AudienceClaimType, "Hello World", StringTypeClaim));  
}

At this point, things get a bit complicated. The FillClaimsForEntity method does not execute inside the same web application or the same application pool as the site that the user is attempting to access. Furthermore, the FillClaimsForEntity method does not run under the identity of the current user who is being authenticated. Instead, the FillClaimsForEntity method runs in a separate application pool named SecurityTokenServiceApplicationPool under the identity of a service account.
The AudienceClaimProvider implements FillClaimsForEntity by creating a SPServiceContext object that is based on an SPSite object that is created from the URL to the Central Administration application. This approach provides flexibility because it does not require hard-coding of any URLs. The code then creates an instance of the SharePoint Server 2010 AudienceManager class and enumerates through each audience to determine whether the current user is a member of that audience.
There is one more complexity concerning the identity of the current user. Although you can obtain the identity of the current user by querying the Value property of the incoming parameter named entity, this string-based identity has a prefix of 0#.w|, which indicates that it is an encoded claims-based identity. The following code shows you how to extract the decoded logon name, which makes it possible to call the IsMember method of the Audience class.
C#
protected override void FillClaimsForEntity(System.Uri context, SPClaim entity, List<SPClaim> claims) {
  if (entity == null) throw new ArgumentException("entity");
  if (claims == null) throw new ArgumentException("claims");

  // Decode user name from SAML token.
  string userLoginEncoded = SPUtility.FormatAccountName("i", entity.Value);
  string userLogin = SPClaimProviderManager.Local.DecodeClaim(userLoginEncoded).Value;

  // Determine whether current user is in any audiences.
  using (SPSite siteCollection = new SPSite(CentralAdminUrl)) {
    SPServiceContext ctx = SPServiceContext.GetContext(siteCollection);
    AudienceManager mgr = new AudienceManager(ctx);
    foreach (Audience audience in mgr.Audiences) {
      if (audience.IsMember(userLogin)){

        // If so, create a new claim and add it to SAML token of current user.
        claims.Add(CreateClaim(AudienceClaimType, audience.AudienceName, StringTypeClaim));
      }
    }
  }
}

At this point, we have addressed the code that adds claims to the user's SAML token. Now, we also must implement the methods of the SPClaimProvider class that interact with the People Picker page.
The first method you must override to accomplish this is FillSearch. This method is called when a user runs a search in the People Picker page. A key observation is that a custom claims provider has the opportunity to return entities in search results that represent custom claims, such as an audience. This search functionality is what enables a site administrator to discover a custom claim and use it to grant permissions on securable objects, such as sites and lists.
When the FillSearch method executes, the text that the user typed into the search text box is passed in the searchPattern parameter. The implementation in AudienceClaimProvider enumerates through each audience and finds each one that matches the pattern. It then creates a picker entity object for each audience match by using a utility method named CreatePickerEntityForAudience, and adds the picker entity object to the column on the right side of the People Picker page by calling the AddEntity method of the incoming searchTree parameter, as shown in the following code.
C#
protected override void FillSearch(System.Uri context, string[] entityTypes, 
                                   string searchPattern, string hierarchyNodeID, 
                                   int maxCount, SPProviderHierarchyTree searchTree) {
  if (EntityTypesContain(entityTypes, SPClaimEntityTypes.FormsRole)) {
    List<string> audiences = new List<string>();

    // Get SPSite object for Central Admininistration.
    using (SPSite ca = new SPSite(CentralAdminUrl)) {

      // Get SharePoint Server 2010 Audience Manager.
      SPServiceContext ctx = SPServiceContext.GetContext(ca);
      AudienceManager mgr = new AudienceManager(ctx);

      // Determine if search string matches any audience names.
      foreach (Audience audience in mgr.Audiences) {
        if (audience.AudienceName.StartsWith(searchPattern, StringComparison.CurrentCultureIgnoreCase))

          // Add any audiences that match search string.
          audiences.Add(audience.AudienceName);
      }
    }

    // Add picker entity for each audience that matches.
    foreach (string audienceName in audiences)
      searchTree.AddEntity(CreatePickerEntityForAudience(audienceName));
  }
}

At first, it might be confusing when you begin to think about picker entity objects. However, you should consider a picker entity object as a representation of a security principal that could be a user, a Windows group, a forms role, or a custom claim. What is important to remember about SharePoint Foundation is that any picker entity object can be used to configure permissions. Furthermore, when you assign a permission to a custom claim or add it to a SharePoint group within a specific site collection, SharePoint Foundation must create a profile for the claim in a special hidden list known as the User Information List. This profile can be seen on the Users and Groups page, and can track several different fields, such as Display Name, Email, Work Phone, and Department.
When you create a custom claims provider, you must implement a method named FillSchema. This method enables you to specify the SharePoint entity profile fields that you want to track in the entity picker objects that represent your custom claims. AudienceClaimProvider provides the minimal implementation and adds the field for Display Name by calling the AddSchemaElement method, as shown in the following code.
C#
protected override void FillSchema(SPProviderSchema schema) {

  // Add schema element for display name.
  schema.AddSchemaElement(new SPSchemaElement(
                              PeopleEditorEntityDataKeys.DisplayName,
                              "Display Name",
                              SPSchemaElementType.Both));
}

Now that you have seen how to add fields to the schema for a claims provider's entity picker objects, we can walk through the utility method named CreatePickerEntityForAudience that was called from the FillSearch method. The method implementation begins by creating a new PickerEntity object and initializing it with an SPClaim object, which is created by calling the CreateClaim method provided by the base class SPClaimProvider. Most of the other properties of the PickerEntity object supply text somewhere inside the user interface of the People Picker page. However, it is important to observe that the CreatePickerEntityForAudience method assigns the name of the audience to the DisplayName item of the EntityData collection. This display name value actually is stored in the User Information List in the claims profile. In some scenarios, in addition to the Display Name, it might make sense to include other entity fields, such as Email and Work Phone.
C#
private PickerEntity CreatePickerEntityForAudience(string audience) {

  // Create and initialize new Picker Entity.
  PickerEntity entity = CreatePickerEntity();
  entity.Claim = CreateClaim(AudienceClaimType, audience, StringTypeClaim);
  entity.Description = ClaimProviderDisplayName + ":" + audience;
  entity.DisplayText = audience;
  entity.EntityType = SPClaimEntityTypes.FormsRole;
  entity.IsResolved = true;
  entity.EntityGroupName = "Wingtip Audience";
  entity.EntityData[PeopleEditorEntityDataKeys.DisplayName] = audience;
  return entity;
}

At this point, there is only one more method to address, named FillResolve. However, you must implement it twice because it is overloaded with two different signatures. The first implementation of FillResolve is the one that is called by SharePoint Foundation when a user clicks the OK button on the People Picker page, which then returns to the Grant Permissions page. This is the implementation that has an SPClaim object as the third parameter. Because any audience claim has already been resolved by the AudienceClaimProvider class on the People Picker page, the implementation is fairly simple, as shown in the following code.
C#
protected override void FillResolve(System.Uri context, 
                                    string[] entityTypes, 
                                    SPClaim resolveInput, 
                                    List<PickerEntity> resolved) {
  if (resolveInput.ClaimType == (AudienceClaimType))
    resolved.Add(CreatePickerEntityForAudience(resolveInput.Value));
}

The second implementation of FillResolve is more complex. It is called when a user types text into the Users/Groups input control on the Grant Permissions page, and then clicks the Check User button. In other words, a user is trying to resolve a user, group, or claim without using the People Picker page. The third parameter is not an SPClaim object, but just a string parameter that contains the text that the user has typed. This implementation of FillResolve takes the text input the user has typed and enumerates through each audience looking for a match. If a match is found, a picker entity is created by using the CreatePickerEntityForAudience method, and it is added to the List of resolved PickerEntity objects. When your code resolves text into a picker entity, the user is able to recognize it because the text is underlined.
C#
protected override void FillResolve(System.Uri context, 
                                    string[] entityTypes, 
                                    string resolveInput, 
                                    List<PickerEntity> resolved) {
  List<string> audiences = new List<string>();
  using (SPSite ca = new SPSite(CentralAdminUrl)) {
    SPServiceContext ctx = SPServiceContext.GetContext(ca);
    AudienceManager mgr = new AudienceManager(ctx);
    foreach (Audience audience in mgr.Audiences) {
      if (audience.AudienceName.StartsWith(resolveInput, StringComparison.CurrentCultureIgnoreCase))
        audiences.Add(audience.AudienceName);
    }
  }
  foreach (string audienceName in audiences) {
    resolved.Add(CreatePickerEntityForAudience(audienceName));
  }
}

At this point, we have walked through the entire implementation of the AudienceClaimProvider. The only thing that remains to examine is how a claims provider is registered. Although it would be possible to write code to explicitly register and unregister a claims provider, SharePoint Foundation provides a utility class named SPClaimProviderFeatureReceiver that does the work for you. You can start by creating a new feature in a SharePoint project and changing the scope to farm scope. Next, add a feature receiver. After you add the feature receiver class, change the base class of the feature receiver from SPFeatureReceiver to SPClaimProviderFeatureReceiver. The reason that this approach makes things easier for you is that the base class SPClaimProviderFeatureReceiver provides implementations of FeatureActivated and FeatureDeactivating, which register and unregister the claims provider in the local farm. All you have to do is override four properties to supply the base class with information about the claims provider to register, as shown in the following code.
C#
namespace WingtipClaimProviders.Features.AudienceClaimProviderRegistration {
  [Guid("24535b36-fee1-4285-a33e-b99e3e52b1e9")]
  public class AudienceClaimProviderRegistrationEventReceiver : SPClaimProviderFeatureReceiver {
    public override string ClaimProviderDisplayName {
      get { return AudienceClaimProvider.ClaimProviderDisplayName; }
    }
    public override string ClaimProviderDescription {
      get { return AudienceClaimProvider.ClaimProviderDescription; }
    }
    public override string ClaimProviderAssembly {
      get { return this.GetType().Assembly.FullName; }
    }
    public override string ClaimProviderType {
      get { return typeof(AudienceClaimProvider).FullName; }
    }  
  }
}


Conclusion

The ability to create custom claims providers for Microsoft SharePoint 2010, described in this article, enables you to move beyond simple security schemes where permissions can be configured only in terms of user account names and groups. By adding custom claims into the SAML security tokens of your users, you can make it possible for site administrators to configure security permissions in terms of new abstractions—such as Users Over 21, Naturalized United States Citizens, Managing Partners—and, as shown in this walkthrough and in the accompanying sample, Audiences, which are defined by using SharePoint 2010.

About the Author

Ted Pattison is an author, instructor, and co-founder of Critical Path Training3 , a company dedicated to education on SharePoint technologies. As a Microsoft SharePoint Most Valuable Professional (MVP), Ted frequently works with Microsoft’s Developer Platform Evangelism group to research and author SharePoint training material for developers early in the product life cycle while in its alpha and beta stages. In 2007, Ted published the first edition of this book for Microsoft Press, titled Inside Windows SharePoint Services 3.0, which focuses on how to use SharePoint as a development platform for building business solutions. Ted also writes a developer-focused column for MSDN Magazine titled Office Space.

Additional Resources

Change History

 

Date Description Reason
February 2011 Initial publication
Links Table
1http://www.criticalpathtraining.com/
2http://www.criticalpathtraining.com/Members/Pages/default.aspx
3http://www.criticalpathtraining.com/
4http://msdn.microsoft.com/en-us/library/ff699494.aspx
5http://msdn.microsoft.com/en-us/library/ee535894.aspx
6http://technet.microsoft.com/en-us/library/ee662538(robot).aspx
7http://msdn.microsoft.com/en-us/sharepoint/ff660758.aspx
8http://msdn.microsoft.com/sharepoint/default.aspx
9http://msdn.microsoft.com/en-us/library/gg430136.aspx
Community Content

Verbiage Error Edit
The paragraph "You must override four methods that return Boolean values to indicate the functionality that the claims provider is able to support. The AudienceClaimProvider claims augmentation provider returns true for each of these methods, as shown in the following code." should read as follows -

You must override four properties that return Boolean values to indicate the functionality that the claims provider is able to support. The AudienceClaimProvider claims augmentation provider returns true for each of these methods, as shown in the following code.

The capabilities of the claims provider is configured through a set of properties and not a set of override-able methods.


Scalable Production-ready Audience Augmentation Provider Edit
To ensure performance and scalability of the solution I propose to make the following enhancements to the Claims Provider:

1. Use Audience GUIDs instead of names
2. Use AudienceManager.Search() and AudienceManager.Resolve() methods to discover and resolve audience claims
3. When augmenting claims, use the AudienceManager.GetUserAudienceIDs() method.

Using the above requires elevating privileges and adding the Application pool identity to the Administrators list in the User Profile Service application.
Assign "Manage Audiences" permission to the account.

Please note with the SAML trusted provider (and Forms) SharePoint may still not allow to execute AudienceManager.Search() and AudienceManager.Resolve().  The workaround is to save the HttpContext, clear it and elevate privileges, then restore the HttpContext after the code finishes running.
Without the workaround you may get an exception, similar to the following: System.UnauthorizedAccessException {"Access Denied")} ... Microsoft.SharePoint.SPSecurity.<>c__DisplayClass4.<RunWithElevatedPrivileges>b__2() at
Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated
secureCode)


There's more information and code samples available at http://belkindesign.com/index.php/blog/claimsprovider



Code Sample Download Edit
The code sample download for this article is behind a members only section on Ted's site.  Please update this as I don't think a public article should reference member only content. $0$0 $0


Does this works for multiple claim types ? Edit
Hi, I am using the above sample to work , it is working for single claim type, but it is not working for multiple claim types. ? Any idea..... ?


Code snippet for FillEntityTypes is incorrect Edit
The code snippet under the description of FillEntityTypes doesn't seem to belong. The code from the associated download makes more sense:
protected override void FillEntityTypes(List<string> entityTypes) {
  entityTypes.Add(SPClaimEntityTypes.FormsRole);
}

Friday, May 4, 2012

install customized claim provider

quote: http://samirvaidya.blogspot.com/2011/02/installing-sharepoint-claims-providers.html

 Installing SharePoint Claims Providers

If you have downloaded the sample code for a Custom Claims Provider from MSDN Code Gallery such as from here:

http://archive.msdn.microsoft.com/odcsp14ta/Release/ProjectReleases.aspx?ReleaseId=4375

You will find that there is a document within the solution called instructions.txt.

If you open the document, these are the contents of the file:

1.  Install assembly to GAC. GAC -i xxx.dll     GAC -u xxx.dll
 
To Install Feature:
1a.  install-spfeature -path SqlClaimsProvider
NOTE:  No need to enable / activate because it is a farm-scoped feature.
 
To Uninstall Feature:
1b.  uninstall-spfeature -identity SqlClaimsProvider

Unfortunately, if you attempt to run the command "install-spfeature -path SqlClaimsProvider", you will receive the following error message: "Failed to find the XML file at location 14\Template\Features\SqlClaimsProvider"

Well, as you can probably guess, the documentation provided in instructions.txt is incomplete.  If you read this MSDN article, you will find additional details on how to utilize install-spfeature:

http://msdn.microsoft.com/en-us/library/ff607825.aspx

Based on this article, you will actually need to do the following to successfully install the SqlClaimsProvider as a farm level feature:

  1. Open Windows Explorer
  2. Navigate to the following directory structure: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\FEATURES
  3. Create directory called SqlClaimsProvider
  4. Beneath this directory, copy the file feature.xml from the Visual Studio solution
  5. Now, open the SharePoint 2010 Management Shell
  6. At the PowerShell command prompt, type install-spfeature -path SqlClaimsProvider
  7. This should now successfully install the SqlClaimsProvider as a farm level feature
  8. Make sure the dll in GAC