Thursday, May 24, 2012

create trusted login provider



Claims Walkthrough: Creating Trusted Login Providers (SAML Sign-in) for SharePoint 2010

SharePoint 2010
Published: August 2010
Summary:  Learn how to create a custom security token service (STS) and then set up a trust relationship between a SharePoint 2010 farm and the custom STS.
Applies to:  Microsoft SharePoint Foundation 2010 | Microsoft SharePoint Server 2010
Provided by:  Andy Li, Microsoft Corporation
Contents
Click to get code1 Download code: Claims Example Trusted Login Provider1

Purpose of a Trusted Login Provider

In this walkthrough, you create a custom security token service (STS) and then set up a trust relationship between a Microsoft SharePoint 2010 farm and the custom STS. The custom STS serves as the authentication provider. When users log on to the SharePoint site, they are first redirected to the logon page of the custom STS. They are redirected back to SharePoint after the authentication.
note Note:
A trusted login provider is an external (that is, external to SharePoint) STS that SharePoint trusts. For definitions of claims terms, see Claims-Based Identity Term Definitions2.
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 SharePoint3.

Scenario: Enabling Access to a SharePoint Site Hosted on an Extranet

The fictitious company Contoso has a SharePoint site hosted on an extranet, which its employees can log on to remotely from home or during business travel. Contoso has a partner company named Wingtip, whose employees are working on a project with Contoso and who need to access documents from the SharePoint site.
To enable the Wingtip employees to log on to the SharePoint site that is hosted by Contoso, Wingtip created an STS that can be used to authenticate its employees. On the Contoso site, the farm administrator set up the trust relationship between the SharePoint farm and Wingtip's STS. When employees from Wingtip try to log on to the Contoso SharePoint site, they are first redirected to their STS to be authenticated, then the STS redirects the user to the Contoso SharePoint site. Because the SharePoint farm trusts the Wingtip STS, it also trusts the security token that is issued by the Wingtip STS.

Step 1: Creating the WingtipSTS Project

  1. Start Visual Studio 2010.
  2. On the File menu, click New Project.
  3. In the New Project dialog box, do the following:
    1. In the left pane, select Other Project Type, click Visual Studio Solution, and then select Blank Solution on the right, as shown in Figure 1.
    2. For Location, type C:\StudentFiles\LabFiles\Module_6\Lab.
    3. For the solution Name, type TrustedLogin.


      Figure 1. New Project dialog box in Visual Studio

      New Project dialog box in Visual Studio
  4. In Solution Explorer, right-click the TrustedLogin solution, click Add, and then click New Web Site.
  5. In the Add New Web Site dialog box, do the following:
    1. Select the ASP.NET Security Token Service Web Site template.
    2. Change Web Location to File System, and the value to C:\StudentFiles\LabFiles\Module_6\Lab\TrustedLogin\WingtipSTS.


      Figure 2. Add New Web Site dialog box in Visual Studio

      Add New Web Site dialog box in Visual Studio
  6. Open the web.config file under the new website. In the appSettings section, change IssuerName to WingtipSTS.


    Figure 3. Change appSettings

    Change appSettings

    note Note:
    The SigningCertificateName (CN=STSTestCert) is the certificate that is used by WingtipSTS to sign the security token.

  7. Click Start, and then click Run.
  8. Type mmc, and then press Enter.
  9. In the Microsoft Management Console, click File, and then click Add/Remove Snap-in.
  10. Under the Available snap-ins field in the left pane, click Certificates, and then click Add.


    Figure 4. Microsoft Management Console displaying the STSTestCert

    MMC displaying the STSTestCert
  11. In the Certificate snap-in dialog box, click Computer Account, click Next, and then select Local Computer.
  12. Click Finish, and then click OK.


    note Note:
    Notice that the SigningCertificate in web.config points to the certificate that is displayed here as STSTestCert.

  13. When setting up the trust between WingtipSTS and SharePoint, we need to tell SharePoint the certificate that is used by WingtipSTS. To do this:
    1. Right-click STSTestCert, select All Tasks, and then click Export.
    2. Click Next. Notice that you can export only the public key from this certificate.
    3. Click Next, and then select DER encoded binary X.509 (.CER).
    4. Click Next. In the File to Export dialog box, type C:\StudentFiles\LabFiles\Module_6\Resources\STSTestCertPub.cert as the file name.
    5. Click Next, and then click Finish.
  14. Close Microsoft Management Console.

Step 2: Testing theWingtipSTS Project Claims

  1. Right-click the TrustedLogin solution, click Add, and then click New Web Site.
  2. In the Add New Web Site dialog box, select Claim-Aware ASP.NET Web Site template. Set Web Location to File System and Value to C:\StudentFiles\LabFiles\Module_6\Lab\TestRPWeb, as shown in Figure 5.


    Figure 5. Add New Web Site dialog box

    Add New Web Site dialog box
  3. Right-click the TestRPWeb project, and then click Add STS Reference.
  4. In the Federation Utility wizard that opens, on the Welcome to the Federation Utility wizard page (see Figure 6), click Next. When prompted with The application is NOT hosted on a secure https connection, click Yes.


    Figure 6. Welcome to the Federation Utility wizard page

    Welcome to the Federation Utility wizard page
  5. On the Security Token Service page, click Use an existing STS option. Type http://localhost:48924/WingtipSTS/FederationMetadata/2007-06/FederationMetadata.xml as the STS WS-Federation metadata document location, as shown in Figure 7.
    note Note:
    This URL might be different in your environment. To find the correct URL, right-click FederationMetadata.xml under the FederationMetadata/2007-06 folder in your WingtipSTS project.



    Figure 7. Security Token Services page with STS option

    STS option dialog box
  6. Click Next, and then click Yes regarding the non-secure connection.
  7. On the Security token encryption page, click No Encryption, as shown in Figure 8.


    Figure 8. Security token encryption page

    Security token encryption page
  8. On the Offered Claims page, click Next, as shown in Figure 9.
    note Note:
    This dialog box does not list the claim types that you defined; this is okay.



    Figure 9. Claims offered on the Offered claims page

    Claims offered on the Offered claims page
  9. In the Summary dialog box, click Finish.
    note Note:
    The previous steps will add the necessary entries in the web.config file of WingtipSTS project so that the website will redirect the user to the WingtipSTS site to authenticate the user and to obtain the user's claims.

  10. Open the web.config file.
  11. Remove requestValidationMode="2.0" from the <httpRuntime> element.
  12. Compile the TestRPWeb project and correct any compile errors.
  13. Under TestRPWeb, right-click Default.aspx, and then select View in Browser. You should be redirected to the logon page of the WingtipSTS site, as shown in Figure 10.
    note Note:
    If you get a page cannot be displayed error, ensure that WingtipSTS is up and running in Visual Studio Web Development.



    Figure 10. WingtipSTS logon page

    WingtipSTS logon page
  14. Type the following credentials:
    • Username: user1@wingtip.com
    • Password: pass@word1 (We do not verify the password; any password will work.)
  15. Click Submit. You are redirected back to the TestRPWeb site. Default.aspx displays all claims that are returned by WingtipSTS.


    Figure 11. Claims returned by WingtipSTS

    Claims returned by WingtipSTS

Troubleshooting a Redirection Error

You may receive the following error when WingtipSTS redirects you back to TestRPWeb:
ID4175: The issuer of the Security Token was not recognized by the IssuerNameRegistry. To accept Security Tokens from this issuer, configure the IssuerNameRegistry to return a valid name for this issuer.
If you receive this error, verify that the thumbprint value of the STSTestCert in the web.config file, under TestRPWeb, is correct.
XML
<issuerNameRegistry 
  type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry,
  Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, 
  PublicKeyToken=31bf3856ad364e35">
  <trustedIssuers>
      <add thumbprint="99fcfe2c70ebb571020ca8aa1b7633dfe1fa1d58" name="http://localhost:48924/WingtipSTS/" />
  </trustedIssuers>
</issuerNameRegistry>
To verify this, open the Certificate MMC and find the thumbprint on the Details tab of the certificate, as shown in Figure 12.


Figure 12. Certificate dialog box showing thumbprint

Certificate dialog box showing thumbprint

Step 3: Defining the Claims Supported by the WingtipSTS Project

  1. Add a class file named UserInfo.cs to the App_Code folder under the WingtipSTS Web Site project.
  2. Add the following using statement to UserInfo.cs.
    C#
    using Microsoft.IdentityModel.Claims;
    
    
  3. Add the following code at the end of the UserInfo.cs file. The WingtipClaimTypes class defines the claims that are supported by WingtipSTS.
    C#
    public class WingtipClaimTypes
    {
        // System.IdentityModel.Claims.ClaimTypes.Email;
        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";
    }
    
  4. Replace the UserInfo class with the following code. This class contains some utility methods that are used by WingtipSTS to retrieve a user's claims and authenticate the user based on the user's credentials.
    note Note:
    This code is only for demonstration purposes. You should not use it in a production environment.

    C#
    public class UserInfo
    {
        // The email address is used as the UserID.
        // Every user has two claims: title and email address. 
        // SharePoint will pick up the email claim and treat it as the identity.
        private static string[] userDB = 
           {
            "user1@wingtip.com:Title:Engineer", 
            "user1@wingtip.com:Email:user1@wingtip.com",
            "user2@wingtip.com:Title:Manager",
            "user2@wingtip.com:Email:user2@wingtip.com",
            "user3@wingtip.com:Title:CEO",
            "user3@wingtip.com:Email:user3@wingtip.com",
           };
    
        // Manually construct a list of users. In a production environment,
        // you should look up 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");
            return allUsers;
        }
    
        public static bool AuthenticateUser(string username, string password)
        {
            // Add your authentication logic here.
            return true;
        }
    
        /// <summary>
        /// A real implementation should look up a directory service or database 
        /// to retrieve a user's claim. The code below 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;
        }
    
        public static string GetClaimTypeForRole(string roleName)
        {
            if (roleName.Equals("Title", StringComparison.OrdinalIgnoreCase))
                return WingtipClaimTypes.Title;
            else if (roleName.Equals("Email", StringComparison.OrdinalIgnoreCase))
                return WingtipClaimTypes.EmailAddress;
            else
                throw new Exception("Claim Type not found!");
        }
    
    }
    
    
  5. The code in the UserInfo.cs file now looks like the following.
    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Microsoft.IdentityModel.Claims;
    
    public class WingtipClaimTypes
    {
        // System.IdentityModel.Claims.ClaimTypes.Email;
        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 class UserInfo
    {
        // The email address is used as the UserID.
        // Every user has two claims: title and email address. 
        // SharePoint will pick up the email claim and treat it as identity.
        private static string[] userDB = 
           {
            "user1@wingtip.com:Title:Engineer", 
            "user1@wingtip.com:Email:user1@wingtip.com",
            "user2@wingtip.com:Title:Manager",
            "user2@wingtip.com:Email:user2@wingtip.com",
            "user3@wingtip.com:Title:CEO",
            "user3@wingtip.com:Email:user3@wingtip.com",
           };
    
        // Manually construct a list of users. In a production environment,
        // you should look up 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");
            return allUsers;
        }
    
        public static bool AuthenticateUser(string username, string password)
        {
            // Add your authentication logic here.
            return true;
        }
    
        /// <summary>
        /// A real implementation should look up a directory service or database 
        /// to retrieve a user's claim. The code below 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;
        }
    
        public static string GetClaimTypeForRole(string roleName)
        {
            if (roleName.Equals("Title", StringComparison.OrdinalIgnoreCase))
                return WingtipClaimTypes.Title;
            else if (roleName.Equals("Email", StringComparison.OrdinalIgnoreCase))
                return WingtipClaimTypes.EmailAddress;
            else
                throw new Exception("Claim Type not found!");
        }
    
    }
    
    
  6. Under App_Code, double-click CustomSecurityTokenService.cs to open the file.
  7. Add the namespace reference to System.Collections.
  8. Replace the GetOutputClaimsIdentity function with the following code. This is the function that returns the user's claim.
    C#
        protected override IClaimsIdentity GetOutputClaimsIdentity( IClaimsPrincipal principal, 
             RequestSecurityToken request, Scope scope )
        {
            if ( null == principal )
            {
                throw new ArgumentNullException( "principal" );
            }
    
            ClaimsIdentity outputIdentity = new ClaimsIdentity();
    
            // Issue custom claims.
            // TODO: Change the claims below to issue custom claims 
            // that are required by your application.
            // Update the application's configuration file to reflect 
            // the new claims requirements.
    
            // outputIdentity.Claims.Add( new Claim( 
                System.IdentityModel.Claims.ClaimTypes.Name, principal.Identity.Name ) );
            // outputIdentity.Claims.Add( new Claim( ClaimTypes.Role, "Manager" ) );
    
            // The Wingtip implementation.
            string username = principal.Identity.Name;
            List<Claim> claims = UserInfo.GetClaimsForUser(username);
    
            foreach (Claim claim in claims)
            {
                outputIdentity.Claims.Add(claim);
            }
    
            return outputIdentity;
        }
    
  9. Compile the WingtipSTS website, and then correct any compile errors.

Step 4: Setting Up Trust in SharePoint

The process of setting up trust between WingtipSTS and SharePoint is basically to register the WingtipSTS as a SPTrustedLoginProvider object in the SharePoint farm.
  1. On the Central Administration site, on the left navigation pane, click Security.
  2. Under General Security, click Manage Trust.
  3. On the Server ribbon, click New.
  4. In the Establish Trust Relationship dialog box, in the Name text box, type STSTestCert so that it will be displayed as shown in Figure 13.


    Figure 13. Establishing trust relationship in Central Administration

    Trust Relationships in Central Administration
  5. Click Browse, and then locate the STSTestCertPub.cer file that you exported earlier.
  6. Click OK.
    note Note:
    Step 4 enables SharePoint to trust all the certificates that are rooted to the STSTestCert certificate.

  7. Add a WinForm project named RegisterSTS to the TrustedLogin solution.
    note Note:
    Ensure that you change the Platform Target to All CPU and .NET Framework to 3.5.

  8. Right-click the RegisterSTS project, and then click Set as Startup Project.
  9. Add a button to the form and change the Text property of the button to Register WingtipSTS.
  10. Double-click the button. This brings you to the event handler function of the button.
  11. Replace the Button1_Click function with the following code. The code creates a SPTrustedLoginProvider object and adds it to the SPSecurityTokenServiceManager.TrustedLoginProviders collection.
    note Note:
    You can also use Windows PowerShell scripts to register an STS with SharePoint. For more information, see Security Cmdlets (SharePoint Foundation 2010)4.

    The code does the following:
    1. Define the claims that will be recognized by SharePoint (in this example, email and title).
    2. idClaim defines which claim type is used to uniquely identify a user.
    3. The AddKnownClaimValue function of the SPTrustedClaimTypeInformation class adds the known claim values to the claim type so that later on, when you do a claim search in the People Picker, you will be able to find them.
    4. An X509Certificate2 object points to the public key that we exported earlier.
    On the constructor of the SPTrustedLoginProvider class, remember to modify the URI of your WingtipSTS (the port number may be different; the WingtipSTS in this sample is hosted at the URL http://localhost:48924/WingtipSTS/default.aspx).
    Warning Warning:
    Do not forget the default.aspx in the URL.

    You can create a custom SPClaimProvider object for your SPTrustedLoginProvider object and register it by using SPTrustedLoginProvider.ClaimProviderName (commented out in the following code). Otherwise, SharePoint automatically creates an SPTrustdClaimProvider object (derived from the SPClaimProvider class) for this SPTrustedLoginProvider object. This SPTrustdClaimProvider object is based on the claim type information that we provided in the registration code.
    https://intranet.contoso.com/_trust/ is the redirect URL after the user is authenticated by the STS.
    C#
           private void button1_Click(object sender, EventArgs e)
            {
                List<SPTrustedClaimTypeInformation> claimMapping = new List<SPTrustedClaimTypeInformation>();
                List<string> strClaimMapping = new List<string>();
    
                SPTrustedClaimTypeInformation idClaim = new SPTrustedClaimTypeInformation("EmailAddress", 
                "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", 
                "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress");
                SPTrustedClaimTypeInformation titleClaim = new SPTrustedClaimTypeInformation("Title", 
                "http://schemas.wingtip.com/sharepoint/2009/08/claims/title", 
                "http://schemas.wingtip.com/sharepoint/2009/08/claims/title");
    
                titleClaim.AcceptOnlyKnownClaimValues = true;
    
                idClaim.AddKnownClaimValue("user1@wingtip.com");
                idClaim.AddKnownClaimValue("user2@wingtip.com");
                idClaim.AddKnownClaimValue("user3@wingtip.com");
    
                titleClaim.AddKnownClaimValue("Engineer");
                titleClaim.AddKnownClaimValue("Manager");
                titleClaim.AddKnownClaimValue("CEO");
    
                // Create the string[] for all claims. This is required for 
                // the construction of the SPTrustedLoginProvider object.
                strClaimMapping.Add(idClaim.InputClaimType);
                strClaimMapping.Add(titleClaim.InputClaimType);
    
    
                X509Certificate2 ImportTrustCertificate = 
                new X509Certificate2(@"C:\StudentFiles\LabFiles\Module_6\Resources\STSTestCertPub.cer");
    
                claimMapping.Add(idClaim);
                claimMapping.Add(titleClaim);
    
                SPSecurityTokenServiceManager manager = SPSecurityTokenServiceManager.Local;
                SPTrustedLoginProvider provider = new SPTrustedLoginProvider(manager, 
                "WingtipSTS","WingtipSTS",new Uri("http://localhost:48924/WingtipSTS/default.aspx"),
                "https://intranet.contoso.com/_trust/", strClaimMapping.ToArray(),idClaim);  
    
                foreach (SPTrustedClaimTypeInformation claimTypeInfo in claimMapping)
                {
                    if (claimTypeInfo.InputClaimType == provider.IdentityClaimTypeInformation.InputClaimType)
                    {
                        continue;
                    }
                    provider.AddClaimTypeInformation(claimTypeInfo);
                }
    
                if (ImportTrustCertificate != null)
                {
                    provider.SigningCertificate = ImportTrustCertificate;
                }
    
    
                //provider.ClaimProviderName = "ContosoCRMClaimProvider";
    
                provider.UseWReplyParameter = true;
    
                manager.TrustedLoginProviders.Add(provider);
                manager.Update();
            }
    
  12. Build the RegisterSTS project, and then run it.
  13. Click the button to register the trusted login provider to the farm.

Step 5: Creating a Web Application That Uses the WingtipSTS Project

  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 – Trusted.
  6. Change the Port number to 443.
  7. In the Security Configuration section, under Use Security Socket layer (SSL), click Yes, as shown in Figure 14.
  8. In the Claims Authentication Types section, do the following:
    1. Click Enable Windows Authentication.
    2. Click Integrated Windows Authentication.
    3. Click NTLM from the drop-down list.
    4. Click Trusted Identity Provider.
    5. Click WingtipSTS.


    Figure 14. Create New Web Application dialog box

    Create New Web Application dialog box
  9. Under Application Pool, select the existing AppPool : SharePointAppPool.
  10. In the Database Name and Authentication section, change the database name to WSS_Content_443. Leave other settings as their defaults.
  11. Click OK to create the web application.
  12. After the SSL web application is created, click Application Management, and then click Create site collection.
  13. Change the web application to https://intranet.contoso.com.
  14. For the title, type Trusted.
  15. Click Browse on the Primary Site Collection Administrator.
  16. On the People Picker, under WingtipSTS, do the following:
    note Note:
    As mentioned earlier, the WingtipSTS Claim Provider is a type of SPTrustedClaimProvder. It is generated automatically by SharePoint when registering the SPTrustedLoginProvider.

    1. Select EmailAddress. It shows that there are three available choices, as shown in Figure 15.
    2. Select user1@wingtip.com, and then click OK.


    Figure 15. People Picker

    People Picker
  17. Click OK to create the site collection.

Step 6: Testing the WingtipSTS Project Authentication

Important Important:
Before you run this test, ensure that you have the WingtipSTS project up and running. You can either right-click the WingtipSTS project and then click View in Browser, or you can deploy it to an Internet Information Services (IIS) website.

  1. Navigate to https://intranet.contoso.com.
  2. In the Multiple Authentication Selector drop-down list, click WingtipSTS, as shown in Figure 16.


    Figure 16. Selecting WingtipSTS from the drop-down list

    Selecting WingtipSTS from the drop-down list
    You are redirected to the logon page of the WingtipSTS website, as shown in Figure 17.


    Figure 17. Logon page of the WingtipSTS website

    Logon page of the WingtipSTS website
  3. Type the credential for site administrator, which is user1@wingtip.com.
  4. After authentication, you are redirected back to the SharePoint site, as shown in Figure 18.


    Figure 18. Redirected back to the SharePoint site after authentication

    Redirected to SharePoint site after authentication
  5. Deploy a Web Part that you created and add it to the home page. Observe and make a note of what claims are added to the user.
  6. On the Site Actions menu, click Site Settings, and then click Users and Groups. Click user1@wingtip.com, and then look for the account name. Note the answer to the following questions:
    • What are the ClaimTypes for user1@wingtip.com?
    • What is the account name for user1@wingtip.com?
    • What does each character in the account name mean? (Decode the account name manually or by using code.)
  7. 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.
  8. Under WingtipSTS, click Title.
  9. Type Manager, and then click Search.
  10. From the search result, double-click Manager to add the "Manager" to the users list, and then click Add, as shown in Figure 19.


    Figure 19. People Picker displaying WingtipSTS employee titles

    People Picker displays WingtipSTS employee titles
  11. Close all Internet Explorer instances to clean up the claims authentication session cookie.
  12. Open a new instance of Internet Explorer and navigate to https://intranet.contoso.com.
  13. Try to log on as user2@wingtip.com. Are you able to log on? What if you use user3@wingtip.com?

Conclusion

In this walkthrough, you learn how to create a custom security token service (STS) and then set up the trust relationship between a SharePoint farm and the custom STS. The custom STS serves as the authentication provider. When users log on to the SharePoint site, they are first redirected to the logon page of the custom STS, and then they are redirected back to SharePoint after the authentication.

Additional Resources

Change History

 

Date Description
August 2010
Initial publication
Links Table
1http://code.msdn.microsoft.com/SharePoint-2010-Creating-c30588a7
2http://msdn.microsoft.com/en-us/library/ee534975.aspx
3http://msdn.microsoft.com/en-us/library/ee534967.aspx
4http://technet.microsoft.com/en-us/library/ee890118.aspx
5http://blogs.technet.com/speschka/
6http://msdn.microsoft.com/en-us/sharepoint/ff660758.aspx
7http://msdn.microsoft.com/en-us/library/ff408262.aspx
8http://msdn.microsoft.com/en-us/library/ff699494.aspx
9http://msdn.microsoft.com/en-us/library/ff953202.aspx
10http://msdn.microsoft.com/en-us/library/gg552609.aspx
11http://msdn.microsoft.com/en-us/library/gg481769.aspx
12http://msdn.microsoft.com/en-us/library/gg251994.aspx
13http://msdn.microsoft.com/en-us/library/gg252020.aspx
14http://msdn.microsoft.com/en-us/library/gg317440.aspx
15http://msdn.microsoft.com/en-us/library/ee535894.aspx
16http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.claims.aspx
17http://msdn.microsoft.com/en-us/library/ee658259.aspx
18http://technet.microsoft.com/en-us/sharepoint/ff678022.aspx
19http://msdn.microsoft.com/en-us/sharepoint/ff420377.aspx
20http://msdn.microsoft.com/sharepoint/default.aspx
Community Content
Problem seeing users in People Picker
I followed instructions carefully, just replaced few names to make them distinct. My MockSTS is registered without errors but the STS does not show up in the People Picker in the left pane with groups. I can see "All Users (MockSTS)" under the "All Users" group but I cannot find or validate any of the hardcoded users (user1@wingtip.com). What is wrong with my set up?

On the previously posted issues, I confirm, if you change the platform to 64 bit when compiling RegisterSTS, error "Farm is unavailable" disappears when trying to get access to the Local farm.
The Local Farm is not Accessible - another resolution
I also got stuck on the line "SPSecurityTokenServiceManager.Local".  I was receiving the message "The Local Farm is not Accessible". 

I took a look at the code for SPSecurityTokenServiceManager.Local, and it calls SPFarm.Local.  I tried to re-implement this method and call SPFarm.Open(ConnectionString), with the connection string to the SharePoint Config Database.  At this point, I received the message "Retrieving the COM class factory for component with CLSID {BDEADF26-C265-11D0-BCED-00A0C90AB50F} failed due to the following error: 80040154." 

Referencing https://msmvps.com/blogs/officept/archive/2011/07/25/clsid-bdeadf26-c265-11d0-bced-00a0c90ab50f-failed-due-to-the-following-error-80040154.aspx, I switched the project from 32-bit to 64-bit, and recompiled the application.  At that point, the code ran successfully.

I thought I'd pass this along, as it took me several hours to get past this issue.
Farm is not accessible. - fixed
Thanks for this article!!!!

CarlosMit,
I had the same issue. 
I was able to fix it by following instructions found in a post on Darrin Bishop's blog.
http://darrinbishop.com/blog/2010/05/the-local-farm-is-not-accessible-cmdlets-with-featuredependencyid-are-not-registered

Before I fixed it, I attempted to go the Powershell as mentinoned in the Walkthrough but when I opened powershell, I
received the same "local farm is not accessible".  this led me to Darrin's blog.

It is a rights issue.  Another person at my company did not get the "local fram is not accessible" when they opened powershell.
This person ran the powershell command with my username as described in the blog post.

I did not get the "local farm is not accessible" message anymore in powershell or in the code in the walkthrough.

Thanks for your blog Darrin!!

Jesse
Creating Trusted Login Providers
Thanks for this article
I am facing problem with IIS configuration

I configure the trusted identity provider successfully and am getting login page  and redirect to sharepoint site after authentication this works only with the "Local" when we open the site in other than the local we are getting error like website cannot find.
Thanks in Advance

Cannot register provider.
Thanks for this article. Very Help full, I how ever have 1
issue that I am struckling to resolve.

I get “The farm is
unavailable.” On the following line of code: SPSecurityTokenServiceManager manager = SPSecurityTokenServiceManager.Local;



I searched on Google and tried everything they said, but
nothing seems to work. I am running as system administrator and have full
permissions on all the databases.

Any ideas would be appreciated.

Please Share what changes have to be made...
I am curious as to what code is missing in point 8 under step 3. I was able to make it work even without that. My only issue was that in the DefaultRealm , I was not including _trust. Once I did it, it is working fine....

If any one needs any help let me know...contact me via : http://sharepoint14hive.blogspot.com/
The download code provided in the article is not working
This is to help people who are trying to use this article. There is a download code provided at the start but it is missing code at point 8 under step 3. We spent around 15 days on this. But now its working finally............ I hope somebody else will be benefited.
Not able to add user4 after registering provider once
I have created custom login provider as mentioned in walkthrough. This walkthrough has three users (user1, user2 and user3). Also I have set up sharepoint site. Here (sharepoint site) I can see three users in people picker. But now I want more users. I don't want to add more users from sharepoint's People & Group.

Please help!
How to add more users
Please can you help me out to add more users after registering trusted login provider?

Thursday, May 17, 2012

debug claim provider



Claims Administration, Audiences and More

E-mail Print PDF

The Need for Claims Administration

Have you ever wondered how to get a list of claims for a specific user and if it's even possible?
There shall be no suspense, it is possible. If you have ever tried to implement user impersonation
(emulating the actual user logging in) you would expect some complexity with having to recreate the
HTTP Context or using unmanaged code, but none of this will be required.

This article is a second part of the series about a Custom Claims Provider using SharePoint 2010
Global Audiences. The first part described how to make sure Global Audiences can be used to
provide full security mechanism and not just targeting. At the authentication instant
(your experience may vary) we have added a claim for each audience a user is a member of,
and made sure the audience claim is discoverable in the People Picker.

At that point the claim could be added to a SharePoint Site access control list (ACL),
and the users properly authorized to the site. What is left to develop is a way for site owners and
administrators to find out which claims are available for a particular user. If you've had a chance
to look at Ted Pattison's proof of concept Audience Claim Provider, you've noticed he's included
a Claims Viewer to enumerate claims for an authenticated user. There's quite a few of them,
depending on the authentication method used to log in.

Let me digress and talk about claims in general: I try to think of claims as having two distinct
purposes - authentication and authorization. From this perspective, there are two classes of
claims - an Identity claim (a unique claim used for authentication and authorization) and other claims
(custom claims or authorization-only claims). That's oversimplification as there are other claims
(besides the Identity claim) that users have assigned depending on the authentication method.

It is the second class of claims (authZ claims) that the Audience claim belongs to. It is this class
of claims that enables the most interesting scenarios in Claims mode of operation in SharePoint 2010.
And it's the set of the authorization claims for a particular user that site owners or admins would
like to see to make informed decisions on security.

The Solution in a Nutshell

Get an identity claim for a user with the People Picker control and supply it to SPClaimProviderOperations.ClaimsForEntity(), which calls FillClaimsForEntity() method of the Custom Claims Provider(s) and returns an SPClaim[] array, containing the authorization claims (for all or specified Claims Providers) for the user. Here it is, a  Simply Working Solution™ in one sentence!
"Check Permissions" at /_layouts/user.aspx also performs a call to SPClaimProviderOperations.ClaimsForEntity().
Check Permissions

Displaying Audience Names

Since we are using Global Audience GUID as a claim value, the Claims Viewer will not show the audience names by default.
To add the names, let's populate a dictionary using AudienceManager.GetUserAudienceIDs(identityClaim, true, ca.RootWeb) in one call, and then add the Audience names to the Claims Viewer Grid.

Identity Claim Format

The last, but not the least is making sure that we pass the user identity to the Audience Manager properly in FillClaimsForEntity() in our Custom Claims Provider.
The entity.OriginalIssuer property will contain "SecurityTokenService" for the actual user that is authenticating, or "TrustedProvider" / "Windows" / "Forms" (see SPOriginalIssuerType) if SPClaimProviderOperations.ClaimsForEntity() call is performed.

Conclusion

And with the site owners and site collection administrators happy it's time to celebrate. Champagne, anyone?
Please contact me with questions and suggestions or leave a comment.
Last Updated on Saturday, 31 December 2011 16:38
 

Custom Claims Provider to the Rescue

E-mail Print PDF

SAML Authentication and the People Picker

Out of the box SharePoint claims provider in SAML mode (SPTrustedClaimProvider) resolves any string a user enters in the People Picker. And this is a good thing, since there's no "standard" user store for this authentication method.
In a live system (that end-users should learn to love) this presents several usability problems, but fortunately they are relatively easy to overcome. You guessed it - a Custom Claims Provider should be used.
There are several sample implementations of Custom Claims Providers already available, so you are not alone.
Let's look at a real-life implementation of a localized Custom Claims Provider with a User Profile service application as a back-end user / claims store.
Before we start, there's a few prerequisites and good-to-haves:

  • SharePoint Server 2010 license: any SKU that includes the User Profile service is suitable. You can still benefit from the Localization section if your SKU is SharePoint Foundation.
  • Multilingual users: if you don't have any multilingual requirements, skip to the User Profile App as a User Store section
  • SharePoint Web application in Claims mode: you'll get the most benefits if SAML authentication is used, and some benefits in Forms/Claims or Windows/Claims mode
  • I will assume you have the User Profile Application running smoothly and your global audiences are compiled and contain members, based on a chosen criteria
  • Please see the References and Credits section and familiarize yourself with the basics of Claims-based identity and access control, as well as the User Profile Application considerations

Localization

Thanks to good folks at Microsoft with the SharePoint Service Pack 1 it is now possible to fully localize a Custom Claims Provider.
To localize the DisplayName of a Custom Claims Provider, override FillDefaultLocalizedDisplayName, and for everything else there's your good old friend SPUtility.GetLocalizedString()

protected override void FillDefaultLocalizedDisplayName(CultureInfo culture, out string localizedName) {
localizedName = SPUtility.GetLocalizedString ("$Resources:DisplayNameText",
"ClaimsProviderResource", (uint)CultureInfo.CurrentUICulture.LCID);
}

Place the referenced resource files into a mapped SharePoint Layouts/Resources folder, for example:
ClaimsProviderResource.en-US.resx, ClaimsProviderResource.fr-FR.resx and ClaimsProviderResource.resx for an invariant culture
Now getting SPClaimProvider.DisplayName will result in a GetLocalizedDisplayName() call and the code in FillDefaultLocalizedDisplayName will run if you choose to override this method.

User Profile App as a User Store

The User Profile app can be synchronized with your company's User Directory of choice and augmented with other information from multiple sources. There's API to help retrieving information from this source, and almost no configuration required to make this work.
Besides the Custom Claims Provider, there's no other code to write, isn't it great?
Make sure the User Profile service app contains the objects you need and then use the UserProfileManager.Search() and UserProfileManager.ResolveProfile() methods to ensure scalability of the solution. These methods allow searching in several built-in User Profile attributes at once. The searchable profile properties are FirstName, LastName, PreferredName, UserName, Office, Title, Department, WorkEmail, SPS-SipAddress, and AccountName.
The search algorithm is quite robust and the beginning of every word is searched. This is very useful in a scenario when a profile property contains concatenated data: "John English | Jean Français".
private ProfileBase[] GetUserProfiles (string searchPattern, SPServiceContext ctxt, Boolean resolveMode)  {
ProfileBase[] Users;
UserProfileManager profileManager = new UserProfileManager(ctxt);
if (resolveMode) { Users = profileManager.ResolveProfile(searchPattern); }
else { Users = profileManager.Search(searchPattern); }
returnUsers;
}
Please note that there are scenarios when keeping the ability to resolve any claim is still useful:
- The User Profile service app may not be available
- The user might be too new and the User Profile synchronization has not been yet completed
- The user may not even be in the user store that is accessible from a SharePoing application (yes, you may need to access more than one user store in the Claims Provider)
- The Custom Claims Provider is a core solution and there are many places where the resolution should work, including non claims-based apps like the Central Administration.
So consider the following logic - if there's no exact match of the identity, you may still offer users a choice to resolve any string that they enter.

Identity Claim Value Type

As specified in the SharePoint Security Token Service Web Service Protocol Specification, the unique user identifier (the Identity Claim) is in the format similar to i:05.t|trusted-sts|user_identifier
Character at position 4 in the above example is "5", which corresponds to the "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" URI.
Most of the examples that you will encounter use this custom claim type, and for a good reason - there are only a handful URIs that are not reserved and result in a ASCII character:
  • Email address: "5", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" - use this claim type if you can
  • UPN: "e", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn" - also possible to use in some scenarios (Office 365)
  • Role: "-", "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" - may already be used, and can cause conflicts potentially
The majority of the other URIs or the URIs that are not listed in the spec will produce a UNICODE character at position 4, and this will cause problems with mapping User Profiles to records in the SharePoint Access Control Lists.
So once again, try to use an email address as an identifier if possible.

Audiences as a Flexible Claims Mechanism

Audiences are above the scope of a site collection and can be used for targeting in OOTB SharePoint. With SharePoint 2010 in claims mode, the audiences can also be used to make authorization decisions, just like user identities. This is a very flexible mechanism for creating compound or simple claims, and the possibilities on how to use the Audiences are almost endless.
SharePoint already includes most of the plumbing for using Audiences, so it's another Simply Working Solution™!
AudienceManager.Search() and AudienceManager.Resolve() methods should be used to ensure scalability of the solution, similar to the UserProfileManager methods.
Using the above methods 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 (or 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 using the methods results in an exception: System.UnauthorizedAccessException {"Access Denied")} ... Microsoft.SharePoint.SPSecurity.<>c__DisplayClass4.<RunWithElevatedPrivileges>b__2() at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode)
//IB: null http context is required in SAML (and Forms) mode so the AudienceManager.Search could return results
HttpContext httpCtxt = HttpContext.Current; HttpContext.Current = null;
//IB: Make sure the application pool accounts for the claims applications are in the User Profile service application administrators for the ProfileManager and AudienceManager methods to work.  
Permissions required: Manage Profiles, Manage Audiences
SPSecurity.RunWithElevatedPrivileges (delegate() {
using (SPSite ca = new SPSite (SPAdministrationWebApplication.Local.AlternateUrls[0].IncomingUrl)) {
SPServiceContext ctxt = SPServiceContext.GetContext(ca);
//IB: Users
profileMatches = GetUserProfiles(searchPattern, ctxt, false);
//IB: Audiences
AudienceManager mgr = new AudienceManager(ctxt);
audiences = mgr.Search(searchPattern); }
});
//IB: restoring the HTTP context
HttpContext.Current = httpCtxt;
//... Now profileMatches and audiences collections contain the items we need.

Claims Augmentation

You don't need to add the identity claim, as it is already present when a user authenticates. However, in order for the audiences claim or another custom claim to be useful, a set of claims need to be added after a user authenticates to SharePoint, and this is called "claims augmentation".
We will override FillClaimsForEntity() method and add Global Unique Identifiers for each audience the user belongs to by calling AudienceManager.GetUserAudienceIDs().
Please note the code will run in a context of a Security Token Service Application when an actual user authenticates, and in the context of the tested Web application when a call to SPClaimProviderOperations.ClaimsForEntity() is made (for example, a site owner uses "Check Permissions" function).
To debug the FillClaimsForEntity() code after deployment: reset IIS and attach your Visual Studio debugger to the SecurityTokenServiceApplicationPool w3wp process and the Web application w3wp process if you are debugging administration functionality.
To find out which w3wp process to attach to, run the commands below from the command prompt (on a Windows Server 2008 R2):
cd %systemroot%\system32\inetsrv
appcmd list wp

In the code sample below remember to provide the identityClaim in a suitable format (see the Identity Claim section). Please also check my post about the administration functionality to see a code sample: Windows/Claims and Trusted Provider/Claims configurations are considered.
using (SPSite ca = new SPSite (SPAdministrationWebApplication.Local.AlternateUrls[0].IncomingUrl)) {
SPServiceContext ctxt = SPServiceContext.GetContext(ca);
AudienceManager mgr = new AudienceManager(ctxt);
ArrayList userAudiences = mgr.GetUserAudienceIDs (identityClaim, false, ca.RootWeb);
foreach (AudienceNameID audienceNameId in userAudiences) { claims.Add (CreateClaim (AudienceClaimType, audienceNameId.AudienceID.ToString(), StringClaimType)); }
}

References and Credits

Implementing Claims-Based Authentication with SharePoint Server 2010 (whitepaper)
Claims-Based Identity and Access Control with a foreword by Steve Peschka: see SharePoint-related sections
Creating Custom Claims Providers in SharePoint 2010 by Ted Pattison and Scot Hillier on a sample Custom Claims Provider with Audience claim augmentation
Custom claims providers for People Picker (SharePoint Server 2010) on TechNet
Claims Based Identity & Access Control Guide with a sample Claims Provider implementation for SharePoint
If you must read only one* article on the User Profile setup and synchronization, read "Stuck on Starting": Common Issues with SharePoint Server 2010 User Profile Synchronization by Spencer Harbar! *Well, you ought to follow the links.
Special thanks to John Holliday and Spencer Harbar for validating the scalability of the solution.

Conclusion

Hopefully by this time you've got enough information to implement your own production-quality Custom Claims Provider.
Now move on to Claims Administration article to get an end-to-end working solution.

Please contact me with questions and suggestions on how to improve the articles (it's work in progress) or leave a comment.
Last Updated on Saturday, 31 December 2011 16:36