Chapter 20. Claims-based authentication, federated identities, and OAuth

This chapter takes a detailed look at claims-based authentication and the security infrastructure behind Microsoft SharePoint apps. After a general overview, it focuses on web-based and HTTP-based scenarios. You will learn how to use Microsoft Windows Identity Foundation (WIF) 4.5 (the official Microsoft claims-based framework) to implement a simple Security Token Service (STS), as well as how to register that STS in SharePoint 2013 so that you can share a common single-sign-on infrastructure between multiple SharePoint sites and even third-party sites. In addition, you will learn how to federate with Windows Azure Access Control Services (ACS). Lastly, the chapter covers OAuth for app authentication and authorization.

Claims-based authentication and WS-Federation

Today’s software solutions always require user authentication and authorization. Quite often, however, each application implements its own authentication method, and users are obliged to remember and manage many different credentials. Think about a typical day in your life: you log on to your domain network when you turn on your computer; you log on to Facebook using its specific credentials; next, you log on to http://www.live.com using your Microsoft Account credentials; then, if you need to access your home banking system, you provide yet another set of credentials specific for that system; and so on. The list of examples could be very long, indeed.

The problem is evident: you and everyone else in today’s digital world have too many sets of credentials to remember, manage, and keep safe. Wouldn’t a better solution be to decouple applications and software solutions from their authentication environments, while taking advantage of a shared set of credentials? In the ideal digital world, you should authenticate once, at the very beginning of the day, and use a worldwide single-sign-on infrastructure.

Now consider the scenario of the emerging cloud-computing offerings. Quite often, you use some services on-premises, such as domain controllers, file servers, ERP, and so forth, as well as online services, such as Microsoft Office 365 (Office Web Apps, Microsoft Exchange Online, SharePoint Online, Microsoft Lync, and so on), Microsoft CRM Online, and some services built on top of the Windows Azure platform. Of course, users of your internal network’s domain should authenticate on the internal network as well as online, and you should avoid multiplying users’ credentials and authentications. In the ideal world, you should federate your internal network with the online services, providing a single-sign-on experience to your users, utilizing a federated trust between your network on-premises and the online services in the cloud.

Furthermore, from a developer’s perspective, it is hard to implement the authentication and authorization logic for each and every software solution that a user implements. It would be better to externalize the authentication infrastructure, concentrating the software implementation on the business logic and rules, eventually providing a custom authorization environment only.

Many software solutions authenticate their users just because they need to authorize access to resources or functionalities based on users’ identities. They do not really need, however, to collect and maintain users’ credentials. From an authorization viewpoint, it suffices to have some information about the users to cluster them in groups or audiences and authorize access to resources based on their properties.

Pushed by these ideas, a few years ago the software market started working on the goal of defining an authentication infrastructure that could be externalized and that could identify every user as a digital identity. In Chapter 19 you learned that a digital identity is essentially a set of claims. Remember that a claim is a statement that is asserted by an issuer about a subject; this statement is assumed to be true by the reader, due to a trust relationship between the reader and the issuer. The externalized authentication provider is generally defined as the identity provider (IP) and often publishes an STS. The application or software solution externalizing the authentication process is called the service provider or relying party. The consumer, who uses the service provider for authenticating with the IP, is generally called the subject. Figure 20-1 portrays an extremely simplified authentication architecture employed by a software solution that uses externalized authentication.

A diagram illustrating how an authentication process based on an external IP works. The end user (subject) has to authenticate against a third party and trusted IP, which upon authentication returns a valid set of information (the digital identity). Then, the subject sends the digital identity to the service provider. The service provider checks the digital identity and, because of a trust relationship with the IP, trusts the end user, too. If the end user is authorized to access the requested resource, based on the information presented in his or her digital identity, the service provider returns the requested content.

Figure 20-1. A simplified schema showing the architecture of a system with externalized authentication.

From a technology viewpoint, these concepts use such specifications as WS-Security, WS-Trust, and WS-*. The final goal of these specifications is to allow for implementing a token-based authentication and authorization system, in which third parties can issue tokens.

In December 2006, an international and multivendor working group defined a specification called Web Services Federation Language 1.1 (WS-Federation), which states its role is to define “mechanisms to allow different security realms to federate, such that authorized access to resources managed in one realm can be provided to security principals whose identities are managed in other realms.”

Note

If you are interested, you can download the full WS-Federation specification document from http://specs.xmlsoap.org/ws/2006/12/federation/ws-federation.pdf. There is also an updated version of the specification, called WS-Federation 1.2, available on the OASIS website, at http://docs.oasis-open.org/wsfed/federation/v1.2/os/ws-federation-1.2-spec-os.pdf.

From a practical viewpoint, WS-Federation defines extensions to the WS-Security and WS-Trust specifications, which support exchange of authentication and authorization claims between federated partners, identities brokering, and protection of claims during their transmission across partners. One of the most interesting features of WS-Federation is the capability to provide federation techniques that you can use in communication based on Simple Object Access Protocol (SOAP), via WS-Security and WS-Trust, as well as in web browser–based environments. The SOAP scenario is often called active requestor, while the scenario based on web browsers is referred to as passive requestor. From the perspective of SharePoint and web/HTTP, you should be most interested in the passive requestor scenario, because it is the only process that you can manage, as well as experience from a user viewpoint.

Note

SharePoint 2013 uses the active (SOAP-oriented) scenario in the communication infrastructure of the service applications. Providing complete coverage of all the WS-Federation scenarios is beyond the scope of this book, however.

Figure 20-2 illustrates a sequence diagram related to the functional schema of WS-Federation in the passive requestor scenario.

A sequence diagram illustrating how the WS-Federation passive requestor works. When a subject requests a resource to a target service provider, the service provider gives back a request for authentication if the subject is not yet authenticated. Then the browser is redirected to the IP, which often is also an STS, for authentication. The IP/STS authenticates the end user and, if the user’s credentials are valid, gives back a token. The browser sends the token to the service provider in order to get back the originally requested resource.

Figure 20-2. The sequence diagram of WS-Federation for the passive requestor scenario.

In Figure 20-2, the passive requestor scenario walks through the following steps:

  1. The web browser (subject) sends a request for a resource to the service provider.

  2. The service provider returns a request for authentication and redirects the browser to the IP/STS of the IP.

  3. The end user authenticates within the IP/STS.

  4. If the credentials are valid, the IP/STS issues a token and returns it to the browser.

  5. The browser sends (via automatic HTTP POST) the issued token to the service provider.

  6. The service provider receives the issued token and validates it against the list of trusted IPs. If the token was issued by a trusted IP, it marks the end user as authenticated and eventually authorizes the subject based on the claims presented in the security token.

  7. If the user recognized by the IP/STS is valid and authorized, the SP accepts the request and returns the originally requested resource.

The term passive derives from the fact that the web browser is unconsciously and automatically redirected to the IP/STS, and then automatically sends the token via POST to the SP. Thus, the browser is passive during the authentication process.

If you share the same IP/STS for two or more sites, such as sharing your Microsoft Account across multiple sites, once an end user has authenticated with the IP/STS, he or she will be able to obtain issued tokens for all of the federated sites without authenticating again. This is a powerful single-sign-on scenario.

Furthermore, when you log on to SharePoint 2013 using claims-based authentication mode, the front end does not redirect you to an external IP/STS for authentication. Instead, it communicates on the back end with the internal IP/STS of SharePoint, using SOAP as the communication protocol.

If you want to realize a complete WS-Federation scenario, you need to register an external IP, together with all the information about its STS. Then you will be able to authenticate with third-party solutions, whereupon you will experience the WS-Federation passive requestor scenario concretely.

When you want to register an external IP, you can use Windows Active Directory Federation Service (AD FS) 2.0, which is available out of the box in Windows Server 2008 or higher; federate with Windows Azure ACS, which will be covered later in this chapter; or implement an IP of your own. Because this book targets developers, the next section will explain how to implement a custom IP from scratch, using Microsoft Visual Studio 2012. Nevertheless, in many cases, you may prefer using AD FS 2.0 or ACS instead of writing custom code.

Implementing an IP/STS with WIF

WIF is a framework natively provided by Microsoft in Microsoft .NET Framework 4.5. WIF supports .NET developers while developing claims-based solutions, whether they work on the service provider side or implement an IP/STS of their own. Targeting .NET 3.5 and 4.0, WIF 1.0 is still available, as well. In fact, SharePoint 2013 internally uses WIF 1.0 with some custom extension libraries to provide OAuth support. The WIF 4.5 runtime is included in the .NET 4.5 runtime, while the WIF 1.0 runtime is available as a free download from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=eb9c345f-e830-40b8-a5fe-ae7a864c4d76.

Note

If you need to develop custom solutions, download the .NET Framework 4.5 software development kit (SDK), which is included in Visual Studio 2012, and the Identity and Access Tool, which is available at http://visualstudiogallery.msdn.microsoft.com/e21bf653-dfe1-4d81-b3d3-795cb104066e. If you want to create custom solutions based on WIF 1.0, download the WIF 1.0 SDK, which is available at http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c148b2df-c7af-46bb-9162-2c9422208504.

WIF 1.0 is compatible with WIF 4.5, so in this chapter you will worth with WIF 4.5 on the IP/STS side. (The WS-Federation active scenario is out of scope for this book.) In the next sections, you will learn how to use WIF 4.5 to implement an IP/STS solution, which can be used to implement a web-based WS-Federation passive requestor scenario, suitable for realizing a single-sign-on user experience shared across multiple sites, whether or not they are implemented with SharePoint. To better follow along, open the .NET solution called DevLeap.IPSTS, which is available in the companion code samples. To work with this code, you must have .NET 4.5, WIF 4.5, and the Identity and Access Tool. Remember, Visual Studio 2012 already includes WIF 4.5 as part of .NET 4.5.

Building an STS

Imagine your company maintains a shared repository of credentials that is based on the standard ASP.NET Membership Providers infrastructure for authenticating users, and you plan to use it for accessing both a SharePoint site and a classic ASP.NET site. To implement a new STS for this scenario, you first need to create a new website project of type ASP.NET Empty Web Application in Visual Studio 2012.

Important

The WIF 1.0 SDK includes an STS Web Site template, but the WIF 4.5 SDK does not. Moreover, because many of the types and namespaces defined in the WIF libraries were renamed and changed between WIF 1.0 and WIF 4.5, you cannot start creating an IP/STS project with WIF 1.0 and then upgrade it to WIF 4.5.

The project template prepares a new empty website project to which you must add a few pages and code files:

  • Default.aspx. A welcome page providing some useful links to interact with the IP/STS. You will find this page in the companion sources, but it will not be discussed in this chapter.

  • Issue.aspx. The page that provides the authentication UI and that wraps the IP/STS service on the back end.

  • FederationMetadata.xml. An XML file providing all the information about the endpoint and the security configuration of the IP/STS. It is fundamental, and, for security reasons, it will be digitally signed. You can create it manually, or you can use some out-of-the-box classes of WCF and WIF to generate it automatically.

Moreover, to use the WIF 4.5 libraries in the IP/STS website project, you need to add references to the System.IdentityModel, System.IdentityModel.Selectors, and System.IdentityModel.Services assemblies.

Next, you need to configure the ASP.NET profile, membership, and role providers. This example uses the ASP.NET Profile engine to store information for custom user profiles, which will be converted into claims. In An excerpt of the web.config file of the IP/STS sample web application, you can see an excerpt of the web.config file of the IP/STS web application. For detailed explanations of the membership and role configuration, please refer back to Chapter 19.

As shown highlighted in bold, the configuration defines a user profile made of four properties:

  • Name. A string representing the user’s name

  • Email. A string representing the user’s email

  • Gender. A string representing the user’s gender

  • Favorite Color. A string providing the user’s favorite color

Later, you will use these profile properties to populate users’ claims. Moreover, in the “Creating a custom claims provider” section, you will authorize users based on their gender and favorite color.

Now consider The ASPX code of the Issue.aspx page: the ASPX code defining the Issue.aspx page. From a UI perspective, this page provides only the controls for authenticating end users. Because in the current sample IP/STS we will use the out-of-the-box Membership Provider API of ASP.NET, the Issue.aspx page will simply contain an ASP.NET Login web control.

As you can see, the core business logic of the Issue.aspx page is behind the OnAuthenticate event of the Login control, which is handled by the loginControl_Authenticate event handler method. By default, the Login control authenticates users by itself, using ASP.NET membership. Nevertheless, to implement a custom IP/STS, you will need to provide some custom code for users’ authentication. A code excerpt illustrating the loginControl_Authenticate event handler method of the Login control implements that method.

Aside from implementing the authentication logic, the event handler simply creates a .NET identity, which is an instance of a type implementing the IIdentity interface, and passes it to a ProcessRequest method, which does the real job from the WS-Federation viewpoint. The full implementation of the ProcessRequest method within the Issue.aspx page implements the ProcessRequest method.

As the code excerpt illustrates, aside from creating an instance of the ClaimsPrincipal type, the ProcessRequest method simply invokes the ProcessRequest method of the FederatedPassiveSecurityTokenServiceOperations type, which is available out of the box in WIF 4.5. That method accepts some arguments related to the current HTTP Request and Response objects, the current user principal, and an instance of a type that inherits from the SecurityTokenService class, which is the real core engine of the IP/STS. The infrastructural types are defined in a dedicated class library project so that the code for the sample project can be better organized.

Note

The code behind the Issue.aspx page does some other things that will not be covered within the text of this chapter. However, you will find the complete and fully functional code in the companion sample.

The source code of the DevLeapSecurityTokenServiceConfiguration class shows the implementation of the DevLeapSecurityTokenServiceConfiguration type, which is defined in the infrastructural class library and handles the creation of the custom SecurityTokenService instance.

The main part of the DevLeapSecurityTokenServiceConfiguration class is the constructor, which uses the base class constructor to define the type of the class inheriting from SecurityTokenService that will implement the STS business logic. In the current example, the class inheriting from SecurityTokenService is the DevLeapSecurityTokenService, shown in The source code of the DevLeapSecurityTokenService class.

The two key points of interest in the DevLeapSecurityTokenService class are the GetScope and GetOutputClaimsIdentity methods. The GetScope method defines the scope of the token issuance. In particular, it defines the X.509 certificate that will be used to sign and eventually encrypt the security token that the IP/STS will release. In the GetScope method, you could also validate the calling relying parties if you want to accept token requests from authorized relying parties only—and generally speaking, you should do that. Moreover, the GetOutputClaimsIdentity method is the core method of the STS and provides, as its result, an instance of the ClaimsIdentity type, which will represent the claims that will be included in the output security token. As shown in The source code of the DevLeapSecurityTokenService class, the DevLeapSecurityTokenService class populates the collection of claims of the current user by accessing his or her user profile and reading the list of available claims from an XML file like the one shown in The XML file with the full list of claims provided by the sample IP/STS.

Notice that the claims defined in The XML file with the full list of claims provided by the sample IP/STS correspond exactly to the user-profile properties declared in the web.config file in An excerpt of the web.config file of the IP/STS sample web application.

Note

Generating the FederationMetadata.xml file is beyond the scope of this chapter, but you will find the file in the companion code samples. To create your own FederationMetadata.xml file, you can try two freely distributed tools from Thinktecture: Federation Metadata Generator (http://static.thinktecture.com/christianweyer/FederationMetadataGenerator_1.0.zip) and the StarterSTS project (http://startersts.codeplex.com/). Be careful, however, because these tools target WIF 1.0, not WIF 4.5. Although they are fine for generating the FederationMetadata tool, you should not use them for creating an IP/STS. Moreover, if you are looking for a ready to go IP/STS solution you can take a look at the IdentityServer project made available by ThinkTecture at the following URL: http://thinktecture.github.io/.

With the fundamental parts of the custom IP/STS implementation in place, you’re ready to consume it, first from an ASP.NET relying party and then from SharePoint 2013.

Building a relying party

To test the IP/STS, you can add a new ASP.NET website project to the current solution by clicking File | New Project in Visual Studio 2012, and choosing an ASP.NET Empty Web Application project model. Next, you need to configure identity federation using the Identity and Access Tool. Right-click the web project in Visual Studio 2012 to access the menu, then choose Identity And Access (see Figure 20-3).

Note

If Identity And Access is not listed on the menu, the tool is not installed. See the instructions at the beginning of the chapter for installation help.

A screen shot depicting the Identity And Access menu choice for configuring identity federation for a target website in Visual Studio 2012.

Figure 20-3. The menu extension to configure the Identity and Access Tool for a web project in Visual Studio 2012.

The Identity and Access Tool prompts you to select whether you want to federate your web app with a local development STS, which is provided out of the box by the Identity and Access Tool; with Windows Azure ACS; or with a business IP/STS like the one in the previous section (see Figure 20-4).

A screen shot showing the UI of the Identity and Access Tool for federating a web application in Visual Studio 2012. It includes a section where you can choose between using a local development STS, using a business IP, and using Windows Azure ACS. Below this section are two fields where you can provide the URL of the FederationMetadata.xml file of the target IP/STS, as well as the realm (that is, the web address) of your application, which will be used to present the relying party to the IP/STS.

Figure 20-4. The UI provided by the Identity and Access Tool for federating a web application in Visual Studio 2012.

For the example, select the Use A Business Identity Provider option and provide the URL of the FederationMetadata.xml file published by the custom IP/STS. Click the OK button to configure your web application according to your choices.

More Info

For further details about WIF, IP/STS, and the Identity and Access Tool, read Programming Windows Identity Foundation, by Vittorio Bertocci (Microsoft Press, 2010) or A Guide to Claims-Based Identity and Access Control: Authentication and Authorization for Services and the Web, by the Patterns & Practices team (Microsoft Press, 2013). You can also read Vittorio Bertocci’s blog, at http://www.cloudidentity.com/, and in particular the post ”A Refresh of the Identity and Access Tool for VS 2012,” from March 2013.

Take a closer look at the web.config file after the Identity and Access Tool modifies it. Two new configuration sections, system.identityModel and system.identityModel.services, were defined targeting the WIF 4.5 infrastructure. The standard ASP.NET authentication method was set to None, because authentication events will be intercepted by an HttpModule class of WIF called WSFederationAuthenticationModule, available in the System.IdentityModel.Services namespace. In addition, a module corresponding to the SessionAuthenticationModule class was registered. This last module avoids repeating authentication against the IP/STS for each request, storing the session security token in a cookie stored securely and locally for the current web application. An excerpt of the web.config file related to the WIF 4.5 sections shows the configuration of the system.identityModel and system.identityModel.services sections of the XML configuration file.

Highlighted in bold, the key points of this listing are:

  • The list of the audience URIs, which are the URLs that represent the relying party.

  • The list of trusted issuers, which are the token issuers that are trusted by the current website. Each trusted issuer is identified by the thumbprint of its certificate. It is important to update this value when moving from a development environment, based on a test certificate, to a production environment using a real certificate.

  • A wsFederation element, which defines the configuration details of the WS-Federation protocol. For example, through this element you can enable the passive requestor profile, the URI of the token issuer, and the realm (that is, the web address) of the relying party. Remember that the realm will be evaluated by the STS to determine whether the current site (relying party) has been authorized to request token issuing or not.

Now, if you start browsing the site, you will be prompted for logging in to the IP/STS before being able to access the relying-party site. To see the real result, however, you need to add a Default.aspx page to the relying-party web project and define a bunch of code for rendering the claims. A code excerpt of the Page_Load event of the Default.aspx page of the relying-party web project provides a code excerpt of the Page_Load event of the Default.aspx page.

As you can see, the code simply defines a LINQ query against the collection of claims of the current ClaimsIdentity instance, corresponding to the currently authenticated user. The result of the LINQ query is bound to a GridView control defined in the ASPX markup of the Default.aspx page. Figure 20-5 shows the result after authenticating with a sample user (assuming you have properly configured users’ profiles).

A screen shot illustrating the default welcome page of the sample relying-party site, showing the claims provided to the currently logged-in user.

Figure 20-5. The output of the Default.aspx page after authentication with a sample user.

SharePoint trusted IPs

As you saw in Chapter 19, SharePoint 2013 uses WIF and the WS-Federation specification as a kind of authentication provider. Thus, you can register the example IP/STS as a trusted IP in SharePoint 2013. To do this, you must complete some configuration steps.

Trusting the IP/STS

To begin, you need to trust the IP from the perspective of SharePoint. Therefore, you need to retrieve the certificate of the IP/STS and register it in the list of trusted issuers of SharePoint. If you are consuming an STS published by a third-party IP, then you can extract the public key of the certificate from the FederationMetadata.xml file, selecting the following XPath node:

EntityDescriptor/RoleDescriptor/KeyDescriptor/KeyInfo/X509Data/X509Certificate

You can simply copy the content of that XML node into a text file and save it with a .cer file extension.

Otherwise, if you are working with an IP/STS published by the same machine on which you are running SharePoint, you can export the .cer certificate file from the local-machine certificate store. You then can import the .cer file into the private SharePoint 2013 certificate store either by using a Windows PowerShell script or the UI of the SharePoint Central Administration (SPCA). In Windows PowerShell, use the following syntax:

$cert = New-Object System.Security.Cryptography.X509Certificates.
X509Certificate2("IPSTSCert.cer")
New-SPTrustedRootAuthority -Name "DevLeap Sample IP/STS" -Certificate $cert

With this cmdlet, you can retrieve an instance of the X509Certificate2 class by referencing the .cer file path, and then load it by invoking the New-SPTrustedRootAuthority cmdlet specific to SharePoint 2013. If the certificate is not trusted by the servers in your SharePoint 2013 farm—for example, if it is a custom self-created certificate—you will have to trust the whole certificate chain in the SharePoint 2013 farm. Executing the script on a single server is sufficient to trust the whole farm.

If you prefer to use the UI of SPCA, browse to the Security section, select Manage Trust, and then in the Trust Relationships ribbon group, click the New button to add a new item. You will have to provide a name and the path to the .cer file to the Establish Trust Relationship page, as shown in Figure 20-6.

A screen shot illustrating the Establish Trust Relationship page, which allows configuring a certificate trust. It includes fields for defining the certificate name and the path of the certificate to trust, as well as some advanced options for trusting an STS of a third-party farm.

Figure 20-6. The Establish Trust Relationship page for registering a new trust relationship.

Registering the IP and mapping claims

Now you are ready to register the custom IP/STS in SharePoint 2013. To begin, define the claims that you would like to manage, and then map them to claims that will be available on the SharePoint side. Each time you authenticate a subject by using an external IP/STS, you have the capability to map the claims emitted by the STS in the security token to claims of the SharePoint side. For example, the custom IP/STS discussed earlier returns a claim of type http://schemas.devleap.com/Claims/Gender, which represents the gender of the current user from the IP/STS viewpoint. In SharePoint, you will have the opportunity to map this claim to another claim type, or you can leave it as-is. The claims-based authentication infrastructure of SharePoint will translate claims for you during user authentication.

Important

The claims-mapping capability is extremely useful and important, because you could have multiple IPs registered for a single web application, and the capability to translate claims from one type to another allows SharePoint to normalize claims during authentication. You also have the capability to implement custom claim providers, inheriting from the class SPClaimProvider, to augment claims of a current principal during the authentication phase.

To register claims mapping, you can use a few commands in Windows PowerShell. Here are the commands for mapping the claims issued by the custom STS:

$map1 = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" -IncomingClaimTypeDisplayName "Email" -SameAsIncoming 
$map2 = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/gender" -IncomingClaimTypeDisplayName "Gender" -SameAsIncoming 
$map3 = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.devleap.com/SampleIPSTS/claims/favoritecolor" -IncomingClaimTypeDisplayName "FavoriteColor" -SameAsIncoming

Here, any email, gender, and favoritecolor claims are left as they are when they come in (see the argument -SameAsIncoming).

The last step for registering an external IP is to create a new entry for the IP in the list of available providers. Again, you can use a Windows PowerShell script to accomplish this:

$realm = "http://claims.sp2013.local/_trust/default.aspx"
$signinurl = "https://localhost:44334/Issue.aspx"
New-SPTrustedIdentityTokenIssuer -Name "DevLeap Sample IP/STS" -Description "DevLeap Sample IP/STS" -Realm $realm -ImportTrustCertificate $cert -ClaimsMappings $map1,$map2,$map3
-SignInUrl $signinurl -IdentifierClaim $map1.InputClaimType

The script defines the $realm variable, which corresponds to the realm of the claims-consumer site. The value of this URL (/_trust/default.aspx, relative to the target SharePoint site) corresponds to a page that will be automatically added to the root folder of your SharePoint web application when you activate a trusted IP as an authentication technique. That page will be almost empty in terms of ASP.NET markup, and it will inherit its behavior from the page TrustedProviderSignInPage, defined in the Microsoft.SharePoint.IdentityModel.Pages namespace. This page will only redirect the user’s browser to the IP/STS logon page.

Another variable defined in the script is the URL of the logon page of the IP/STS ($signinurl). Finally, the script registers a new SPTrustedIdentityTokenIssuer instance by invoking the cmdlet New-SPTrustedIdentityTokenIssuer. The arguments provided to this cmdlet in the previous example are for the name and description of the new IP, the realm of the target SharePoint site, the X.509 certificate of the IP/STS, and the sign-in URL, claims mappings, and type of the claim that will be considered as the identifier claim for the authenticated subject.

Configuring the target web application

To complete the configuration process, you need to add the new IP to the list of authentication providers for the target web application. On the SPCA page, in the Application Management section, click Manage Web Applications. A window appears that presents the list of all the available web applications. Choose the web application for which you want to enable the IP/STS as one of the authentication methods. Next, on the ribbon, click the Authentication Providers command. In the window that appears, click the Default Configuration hyperlink. The Edit Authentication configuration page opens, as shown in Figure 20-7. Here, you can select the new IP.

A screen shot showing the Edit Authentication page for configuring the type of authentication you want to support with a web application. It includes options for choosing Windows Authentication, Forms-Based Authentication (FBA), and federating with trusted IPs.

Figure 20-7. The Edit Authentication configuration page of SPCA.

That’s it! Now you’re ready to authenticate your users by using the custom IP/STS. Figure 20-8 shows the authentication options that are presented to any end user willing to authenticate.

A screen shot showing the default authentication page presented to the end users while logging on to a site in a web application supporting multiple authentication methods. There is a drop-down list for choosing the target authentication method. In the current sample, the available options are Windows Authentication, Forms Authentication, and DevLeap Sample IP/STS.

Figure 20-8. The authentication options displayed to the end user.

The DevLeap Sample IP/STS option will redirect the user to the logon page of the IP/STS. Of course, if you configure the IP as the unique authentication provider, your users will be redirected automatically to the IP/STS without stepping into the authentication method selection page.

Now you will also be able to configure users authenticated by the IP as specific SharePoint users and give them specific permissions. Figure 20-9 shows the Share dialog window, with a search result obtained by searching against the currently configured IP.

A screen shot showing the page for adding people and groups to SharePoint. The window provides IntelliSense support for looking through the available claims.

Figure 20-9. The Share window of SharePoint for adding people and groups.

If you try to access the sample site you defined in the “Building a relying party” section, you will be authenticated automatically and have access to the site. Thus, you are experiencing a real single-sign-on user experience.

Creating a custom claims provider

When SharePoint authenticates a user via claims-based authentication, it engages a claim provider, which is a class providing claims augmentation and name resolution utilities. Claims augmentation allows for adding some custom claims to the security token retrieved by the authentication infrastructure. Name resolution allows for adding capabilities to search, resolve, and provide friendly values for claims, people, and roles in the PeoplePicker control.

Depending on the authentication type you use, SharePoint will access one of three default claims providers:

  • SPActiveDirectoryClaimProvider. Used by Windows Authentication

  • SPFormsClaimProvider. Used by FBA

  • SPTrustedClaimProvider. Used by SAML-based (IP) authentication

The claims provider engaged for SAML-based tokens provides claim augmentation capabilities, but it does not provide real name-resolution functionality. In fact, when you shared your site with people and groups, as shown in Figure 20-9, you were simply using a fake model for claims and name resolution. The PeoplePicker control accepts any text value you provide to it and resolves it as if it is a real claim value provided by the federated IP/STS. Unfortunately, this behavior can lead to confusion for the end users. Usually, when using SAML-based authentication, you should also implement a custom claims provider to fix this standard behavior.

To better experience this issue, open SPCA and select the Manage Web Applications menu item in the Application Management menu group. Then select the web application you previously configured for using the external IP/STS, and click User Policy on the ribbon. If you add a new user policy from the resulting dialog box, and you choose to search for a specific set of users or roles while within the PeoplePicker control, you will see the search dialog box shown in Figure 20-10.

A screen shot illustrating the UI of the standard PeoplePicker control dialog box, during a search for users or roles. The dialog box allows you to select people or groups based on the authentication provider, within the set of authentication providers configured for the current web application. Moreover, the IP/STS authentication provider allows you to search people or groups based on specific claim values.

Figure 20-10. The Select People And Groups dialog box of a PeoplePicker control.

Within the Select People And Groups dialog box, you can search for people and groups, based on claims values. You will be able to write any text value, however, even if that value does not exist or is not handled by the federated IP/STS. To fix this behavior, you will need to implement a custom claims provider.

Note

The sample illustrated in this chapter is based on the article “Claims Walkthrough: Writing Claims Providers for SharePoint 2010,” by Steve Peschka, available on TechNet, at http://msdn.microsoft.com/en-us/library/ff699494.aspx.

A custom claims provider, like those available out of the box, is just a class that provides claims augmentation and name resolution capabilities. An excerpt of a sample claims provider class for supporting custom claims provides an excerpt of a sample claims provider class, supporting the claims provided by the custom IP/STS illustrated previously.

The class was created in a .NET 4.5 Class Library project, which references the basic Microsoft.SharePoint.dll assembly and the Microsoft.IdentityModel.dll assembly for WIF 1.0. The basic idea of this sample claims provider is to provide predefined values for the gender and favoriteColor claims, as well as to augment the security token of authenticated users with a fidelityProgramLevel claim, which can assume only four values: Bronze, Silver, Gold, or Platinum.

Although the companion code provides claims augmentation and name resolution functions, the code illustrated in An excerpt of a sample claims provider class for supporting custom claims simply defines the basic infrastructure of the class. As you can see, the custom claims provider class inherits from the SPClaimProvider abstract class, which is available in the Microsoft.SharePoint.Administration.Claims namespace of the Microsoft.SharePoint.dll assembly. The SPClaimProvider base class provides many members that can be overridden, depending on the type of capabilities you want to provide through your custom claims provider. First of all, and regardless the type of claims provider you are implementing, you need to override the Name property to provide a name unique at the farm level for the custom claims provider.

To implement name resolution, you need to override the following abstract methods:

protected abstract void FillSchema(SPProviderSchema schema);
protected abstract void FillClaimTypes(List<String> claimTypes);
protected abstract void FillClaimValueTypes(List<String> claimValueTypes);
protected abstract void FillEntityTypes(List<String> entityTypes);

To implement claims augmentation, you must override the following members:

public abstract bool SupportsEntityInformation
protected abstract void FillClaimsForEntity(Uri context, SPClaim entity,
    List<SPClaim> claims);

Optionally, you can override members to support hierarchies, to resolve claims, or to support searching claims:

public abstract bool SupportsHierarchy
protected abstract void FillHierarchy(Uri context, String[] entityTypes,
    String hierarchyNodeID, int numberOfLevels, bool includeEntityData,
    SPProviderHierarchyTree hierarchy);
public abstract bool SupportsResolve
protected abstract void FillResolve(Uri context, String[] entityTypes,
    String resolveInput, List<PickerEntity> resolved);
protected abstract void FillResolve(Uri context, String[] entityTypes,
    SPClaim resolveInput, List<PickerEntity> resolved);
public abstract bool SupportsSearch
protected abstract void FillSearch(Uri context, String[] entityTypes,
    String searchPattern, String hierarchyNodeID, int maxCount,
    SPProviderHierarchyTree searchTree);

As you may gather from the names of the abstract properties, you need to declare your support for any specific functionality. For example, if you want to support search capabilities, you will need to override the Boolean SupportsSearch property, returning a value of true, and then you will have to override the FillSearch method. An excerpt of a sample claims provider class, showing the FillSearch custom method shows a code excerpt of the implementation of the FillSearch method, which is invoked by the PeoplePicker control when searching for a specific value.

Now you are ready to deploy the custom claims provider implementation. To achieve this, you need to create a SharePoint farm-level solution with a custom feature and a feature receiver in it. The only goal of the farm-level solution is to copy the assembly containing the custom claims provider into the Global Assembly Cache (GAC) of the servers in the SharePoint farm.

Important

Because you need a farm-level feature, you will not be able to use a custom claims provider in Office 365—all the information you are reading about custom claims providers is only suitable for an on-premises scenario.

Moreover, you will have to implement a specific kind of feature event receiver that inherits from the SPClaimsProviderFeatureReceiver class. You will use it to enable the claims provider on the farm by settings its IsUsedByDefault property to a value of true. By default, when you install a claims provider onto a target farm, it is configured as disabled. An excerpt of the feature receiver for deploying a custom claims provider details the feature receiver used to deploy the custom claims provider described in this section.

After installing and deploying the solution and activating the feature, you will have to map the custom claims provider with the target web application in which you want to use the provider. To map a web application to a specific claims provider, you can use a small PowerShell script like the one A PowerShell script for registering a custom claims provider onto a target web application.

More Info

For further details about how to deploy a custom claims provider, you can read the article “How to: Deploy a claims provider in SharePoint 2013,” available at http://msdn.microsoft.com/en-us/library/ee535443.aspx.

Now you are ready to check the result. Back on the User Policy page of the web application, check the new capabilities that you will find in the Select People And Groups dialog box. Figure 20-11 illustrates the new layout of the dialog box. By searching a particular value, like the value Gold for the fidelity program level, you will see the result highlighted in the proper claim node.

A screen shot illustrating the Select People And Groups dialog box. In the left hierarchy is a new node related to the custom claims provider, with the three claims defined (Gender, Favorite Color, and Fidelity Program Level).

Figure 20-11. The Select People And Groups dialog box of a PeoplePicker control with the custom claims provider configured.

Consider that the sample claims provider discussed in this section augments claims, too. In fact, after installing the custom claims provider in the list of users’ claims, you will find a fidelityProgramLevel claim. Figure 20-11 shows the presence of the new custom claim provider, as you can see in the DevLeap Claims Provider item in the hierarchy on the left side of the screen.

While in Figure 20-12 you can see the claims of the currently logged in user, in particular you can see the gender, favoriteColor, and fidelityProgramLevel claims.

A screen shot showing the list of claims assigned to a currently logged-in user. Outlined in red are the Gender and Favorite Color claims, as well as the augmented Fidelity Program Level claim.

Figure 20-12. The list of claims related to a logged-in user, after claims augmentation.

Federating with Windows Azure ACS

So far, you have seen how to create a custom IP/STS, how to configure a SharePoint web application to use the IP/STS, and how to define a custom claims provider to provide end users with a better experience. You will probably agree, however, that the process is not overly easy, and using an out-of-the-box solution would be better than developing so much code. Luckily, Windows Azure offers ACS, an out-of-the-box IP/STS service that supports custom IPs, as well as such consolidated and well-known authentication engines as Facebook, Windows Live ID, Google, Active Directory Federation Services (AD FS) 2.0, and more. In this section, you will learn how to take advantage of Windows Azure ACS in SharePoint 2013. Before you begin, either create a Windows Azure account and a subscription, or log in to the management portal of Windows Azure, (https://manage.windowsazure.com/) with your existing account.

In the management portal, focus your attention on the Active Directory group of services. Here, you can create a new ACS namespace. Figure 20-13 illustrates the controls to use.

A screen shot showing the interface for creating a new Windows Azure ACS namespace. It includes a text box to provide a name for the namespace and a drop-down control to select the region where you want to create the service instance.

Figure 20-13. The UI for creating a new Windows Azure ACS namespace.

Simply provide a name for the target namespace, choosing a name unique in the Windows Azure ACS world, and a region where your service will be provisioned. Click Create, and the new service instance will be ready to work with. Select it, and click the Manage button in the lower command bar of the management portal, to manage the service. You will be presented with a dedicated web management portal like the one shown in Figure 20-14.

A screen shot illustrating the home page of the web portal for managing a Windows Azure ACS instance. On the left are options to configure IPs, relaying parties, rule groups, certificate and keys, service identities, portal administrators, the management service, and application integration. The main body of the home page walks you through the steps for configuring the ACS service instance.

Figure 20-14. The home page of the web portal for managing a Windows Azure ACS instance.

The home page of the Windows Azure ACS instance management portal provides links to configure all the various aspects of the service. First, you need to choose and configure the IPs. By default, every ACS service instance is configured to authenticate users using Microsoft Account, but you can configure as many IPs as you want, as long as they fall into one of the following categories:

  • WS-Federation. Defines all the available federation services that are compliant with the WS-Federation specification. For instance, AD FS 2.0 is one possible option for this category.

  • Facebook. Allows use of Facebook as an external IP.

  • Windows Live ID. Uses the Microsoft Account IP offered by Microsoft.

  • Google. Uses Google as the IP for authenticating users.

  • Yahoo! Uses Yahoo! as the IP for authenticating users.

Imagine that you want to provide authentication services using Facebook users’ credentials or Microsoft Account. To use Facebook, first you must create and configure a Facebook app on the Facebook developer portal: log in to the Facebook developer portal (http://developers.facebook.com) and choose to create a new app. You will have to configure at least the Site URL of your app, which will be the URL of the Windows Azure ACS service instance. Figure 20-15 shows the Facebook app configuration panel.

A screen shot showing the page for managing the configuration of a Facebook app. Among the many configurable fields are fields for the app ID, app secret, and site URL of the app, which will be useful to configure the Windows Azure ACS integration.

Figure 20-15. The page for managing the configuration of a Facebook app.

At the very top of the page, notice the app ID and the app secret for the current app. You will need these to properly configure the Windows Azure ACS integration with Facebook. Behind the scenes, ACS uses OAuth to talk with Facebook and converts the OAuth context information into claims in a security token that will be provided to SharePoint 2013. After creating the Facebook app, go back to the management site for your ACS service and click the Identity Providers menu on the left side of the home page. Choose to add a new Identity Provider and select Facebook as the type. You will be prompted with a page like the one shown in Figure 20-16.

A screen shot illustrating the page for creating a new IP based on Facebook. It includes text fields for configuring the display name of the IP, the application ID, the application secret, the permissions, and some other graphical information, such as a name and a picture to use for presenting the IP to the end users.

Figure 20-16. The page for adding a new IP based on Facebook.

On this page, you will have to configure the Application ID field with the value of the app ID taken in Facebook, and the Application Secret field with the value of the app secret taken from Facebook. Save the new IP.

The next step is to configure the relying parties. Click the Relying Party Applications menu item on the left of the ACS management portal to access the page shown in Figure 20-17. Here, you can create as many relying parties as you want. Every single relying party will participate in the unique single-sign-on experience provided by the ACS IP. For this example, simply configure a target SharePoint web application. Let’s say the URL of the target SharePoint web application is http://claims.sp2013.local.

A screen shot showing the page for adding a new relying party to Windows Azure ACS. It includes fields for configuring the name, the configuration mode, the realm, the return URL, and other parameters of the target relying party.

Figure 20-17. The page for creating a new relying party in Windows Azure ACS.

To configure a SharePoint 2013 relying party, aside from providing a name for the relying party, you must also configure the realm and the return URL targeting the /_trust/default.aspx relative URL. Thus, for the sample web application with URL http://claims.sp2013.local/, you need to provide both for the realm and for the return URL the value of http://claims.sp2013.local/_trust/default.aspx. While configuring a new relying party, you will also have the opportunity to choose which IP will be available for each relying party. In this case, assume the default Windows Live ID and Facebook. Next, choose the format of the SAML token that will be sent back to the relying party. For SharePoint 2013, choose a SAML 1.1 token, unless you do not want to customize the out-of-the-box capabilities of SharePoint.

Figure 20-18 shows the second part of the page for creating a relying party. Notice the options for configuring the IPs, the SAML token format, and the token lifetime in seconds. The token lifetime should be larger than the corresponding value configured in SharePoint, which by default is 600 seconds. For example you can use a value of 3000 seconds or more. The available range for the token lifetime is between 0 and 86400 (1 day).

A screen shot depicting the second part of the page for creating a new relying party. It includes fields to configure the SAML token format, as well as the IPs that will be available while authenticating users for that specific relying party.

Figure 20-18. The second part of the page for creating a new relying party in Windows Azure ACS.

From the same page, you can define the rules for signing and encrypting the tokens, and you can also provide a custom X.509 certificate dedicated to a specific relying party.

After creating one or more relying parties, you need to configure how Windows Azure ACS will handle and eventually transform the claims received from the external IPs before sending the security tokens to the target relying parties. In fact, ACS can apply transformations and translations of claims before sending the security tokens to the target relying party. By default, you can create a set of automatic rules, but if necessary, you can also define simple translation rules that can read a claim and provide another claim or a fixed value as output. Creating rules is mandatory, and by default ACS has no rules defined. Click the Rule Groups menu item on the left of the management site, and then click the Generate button in the middle of the page. Figure 20-19 illustrates the page for generating rules.

A screen shot presenting the page for creating new rules to apply on claims in Windows Azure ACS. It includes a few links and buttons for automatically generating rules and manually creating explicit rules.

Figure 20-19. The page for creating rule groups in Windows Azure ACS.

So far, you have configured the Windows Azure ACS service for SharePoint integration. On the ACS management site, there are some other pages for configuring certificates, signing and encryption keys, assigning identities local to the ACS service, and defining administrators of the ACS service. To federate SharePoint 2013 with ACS, however, you don’t need to bother with these. Simply click the Application Integration menu item to see the URLs that you will have to use to integrate SharePoint with ACS. Figure 20-20 shows the resulting Application Integration page.

A screen shot illustrating the Application Integration page. The page provides a list of all the available URLs for federating with ACS, either using OAuth WRAP (Web Resource Authorization Protocol), OAuth 2.0, or WS-Federation. It also provides URLs for managing ACS from external systems.

Figure 20-20. The Application Integration page for integrating external applications with Windows Azure ACS.

From this page, you will have to navigate with a web browser to the WS-Federation Metadata URL. There, you will find the X.509 certificate used by ACS to sign the security tokens that will be sent to SharePoint. As described previously, in the “Trusting the IP/STS” section, you will have to copy the text content of the following node:

EntityDescriptor/RoleDescriptor/KeyDescriptor/KeyInfo/X509Data/X509Certificate

Then you must save the copied text into a file with extension .cer. The last thing to do is execute some PowerShell commands to federate SharePoint 2013 with ACS. A PowerShell script to federate Windows Azure ACS with SharePoint 2013 provides a sample PowerShell script for this task.

As you can see, the script is almost the same as the one used in the “Registering the IP and mapping claims” section. Now the ACS IP is ready to be used. In SPCA, edit the authentication providers of a target web application and add the new IP to the list of the trusted IPs. Figure 20-21 shows the UI with two IPs available: the custom one and the ACS IP.

A screen shot showing the page for registering one or more trusted IPs for a target web application. The page lists all the available authentication methods as well as the trusted IPs.

Figure 20-21. The page for configuring trusted IPs for a target web application.

As soon as you add the new trusted IP, you will be able to authenticate using Windows Azure ACS. Figure 20-22 shows the authentication options provided to the end users.

A screen shot illustrating the page for selecting the authentication method for accessing a target web application. It includes all the options previously configured: Windows Authentication, Forms Authentication, the custom DevLeap Sample IP/STS, and SP2013 ACS (for Windows Azure ACS).

Figure 20-22. The page for selecting the authentication method for accessing a web application.

Figure 20-23 shows the logon page provided by Windows Azure ACS, where end users can choose to authenticate using Windows Live ID or Facebook. Be aware that the page provided by Windows Azure ACS is autogenerated with a standard and very simple template. However, you can customize this page with your own layout.

A screen shot illustrating the page for authenticating against Windows Azure ACS. It includes two large buttons: one for authenticating with Windows Live ID and one for authenticating via Facebook.

Figure 20-23. The logon page provided by Windows Azure ACS.

Click the Facebook button and you will be redirected to the standard Facebook login page, which will provide information about the target app that is requesting authentication. In the current example, the Facebook app name is SP2013-Reference. Figure 20-24 shows the Facebook login page.

A screen shot illustrating the login page of Facebook. The page provides the classic fields for authenticating using email/phone and password. The page also provides information about the target Facebook app that is requesting the user’s authentication.

Figure 20-24. The login page of Facebook while authenticating through Windows Azure ACS.

After authenticating, the end users will be prompted with a request to authorize the Facebook app (which in reality will be ACS) to access some of the profile information of the currently authenticated user. The profile information and properties will be those you configured while creating the IP in ACS. Facebook will prompt this page (Figure 20-25) to each end user only the first time he or she authenticates using that Facebook app.

A screen shot showing the Facebook page that requests authorization to provide the user’s information to the target Facebook app. The page illustrates the information that will be provided to the target app, which is ACS.

Figure 20-25. The page of Facebook for authorizing Windows Azure ACS to access the user’s profile information.

Clicking the Go To App button redirects your end user to ACS and then to SharePoint 2013. Remember that you are using a WS-Federation passive requestor, so the user will be redirected passively back and forth between SharePoint, ACS, and the external IP.

If the user is authorized to access SharePoint, you will be able to find a rich set of claims describing his or her digital identity. Figure 20-26 shows the home page of the sample web application, which browses all the claims available in the currently logged-in user’s profile. As you can see, there are claims providing information about the email, the name, and the Facebook session ID. If necessary, you will be able to read this information from the identity of the current user, which is of type ClaimsIdentity, and, for example, use the Facebook APIs to retrieve additional information, as long as the user provided you with authorization to do so.

A screen shot illustrating the home page of the target web application used for authenticating via ACS and Facebook. It includes a custom web part showing all the claims available in the current user’s identity.

Figure 20-26. The home page of the sample web application after an end user has been authenticated with ACS and Facebook.

Notice that the current web application is also configured for using the custom claims provider created previously. Thus, in the list of users’ claims, you will still find the Fidelity Program Level claims. This means that the custom claims provider augments the claims of an authenticated user regardless of the IP you used to authenticate him or her.

Understanding OAuth

So far, you’ve learned how the authentication engine of SharePoint behaves when authenticating users and roles in a claims-based world. What about SharePoint apps? As you remember from Chapter 8 every app has a security principal of its own, called the app principal, and whenever a SharePoint app needs to consume a SharePoint site, an authentication and authorization process based on the OAuth protocol takes place.

OAuth is the protocol that defines how to manage all the phases for authenticating an app against a remote repository of data and a remote API, as well as how to authorize that app to perform exactly a well-defined set of operations. An open protocol, OAuth authenticates apps and enables secure API authorization from desktop and web applications through a standard, web-based technique.

Nowadays, every web application provides some content and features to authenticated users. Think about SkyDrive, Flickr, Facebook, LinkedIn, and similar sites. Each requires users to authenticate by providing credentials and allows authenticated users to manage their personal data. Take SkyDrive as an example. You can log into SkyDrive using your Microsoft Account; you can upload content, share content with others, and read content shared with you by someone else. Moreover, you can use a Windows Store app, running within a Windows 8 tablet PC, to read or write files stored on your SkyDrive storage. The same thing could happen using an iPhone, an iPad, or any other device capable of consuming the APIs published by SkyDrive. Furthermore, suppose you want to share your photos stored on SkyDrive with external services, such as an external photo-printing service. Usually, when you need to share your content with someone else or with an external app, you should not share your user credentials with any of the apps or users with whom you share your content. In fact, if you were to share your credentials, those users or external apps would have exactly the same rights and capabilities you would have for your own data, including the capability to delete your files, change your permissions, and even change your password. Of course, this would be too much. On the contrary, you usually authorize external users or apps to do something against your own data, keeping you as the only owner of that data and providing to the third parties only those permissions that are effectively required, usually for a limited period of time. For example, think again about the photo-printing service. You would probably allow an external photo-printing service to access your photos on SkyDrive only for reading, and perhaps for only half an hour—just enough time to download and print the photos. But how is it possible to share this content with third-party apps without sharing you user credentials, and with imposed time limits?

In SharePoint 2013, whenever a SharePoint app wants to access content related to a site or a specific user, the authentication and authorization engine works as illustrated in the schema in Figure 20-27.

A diagram illustrating the authentication flow, which is executed by SharePoint 2013 when authenticating any request sent to the web front-end servers, either coming from an end user or coming from an app via OAuth.

Figure 20-27. A functional diagram of SharePoint 2013 authentication, including OAuth.

When SharePoint 2013 begins to authenticate an incoming request, it first looks to see if the incoming request contains a SAML token with a user identity. If SharePoint finds a SAML token, it can then assume that the incoming request was initiated by an end user, not by an app. Once it finds a SAML token, SharePoint 2013 then inspects the target URL of the incoming request to see whether it references a standard SharePoint site or a child site associated with a specific app. If the incoming request targets a standard site, SharePoint 2013 handles authentication and authorization tasks as described in previous sections. If the incoming request targets an app web, SharePoint 2013 initializes the call context with both a user identity and an app identity.

When an incoming request does not contain a SAML token, SharePoint 2013 knows that a user did not initiate the request. In this scenario, the SharePoint 2013 authentication pipeline inspects the incoming request to see if it contains a security token identifying a developer or a hosted app. Once SharePoint 2013 finds a security token identifying an app, it sets up a call context with the app identity, and optionally the user identity as well.

While invoking the CSOM or the new REST APIs, SharePoint will expect and validate the security token, and will provide access to content and APIs according to the permissions provided to the target app, and to the user for which the app is acting.

Internally, the OAuth protocol uses an app ID, which uniquely identifies every app, as well as an app shared secret, which allows every app to communicate securely with the target service provider or API, being able to secure communication and authenticate against the target service provider or API as a specific app. When the service provider, which could be SharePoint 2013, authorizes the app to do something, or does not authorize the app to do something, it evaluates the authorization rules both of the app and of the current end user. If both of them have the rights for the APIs that are requested, then the result is consent; otherwise; it will be a denial.

In Chapter 8, you learned that when you create a SharePoint app, you can create an app ID or client ID and a shared secret, using the Seller Dashboard for the Office Store (if you are using Microsoft Office 365), or using some dedicated administrative pages (if the app targets an on-premises environment). In both cases, SharePoint 2013 uses OAuth in conjunction with Windows Azure ACS.

Remember, however, that SharePoint 2013 uses OAuth only for authentication and authorization of apps and for consuming the CSOM. All the other authentication and authorization techniques ignore the OAuth protocol and maintain their classic way of working.

Configuring server-to-server apps

Sometimes, while defining the security context of an app that will be used on-premises, you may not want to define an app ID and an app shared secret. Instead, you would prefer to trust an app, without relying on Windows Azure ACS, OAuth, and so on. Luckily, there is a suitable option that allows working in a high-trust, or server-to-server (S2S), configuration. This configuration involves sharing between the app and the target SharePoint farm of an X.509 certificate, which will be used to secure and authenticate the communication between SharePoint and the target app. To configure the S2S scenario, follow these steps:

  1. Access the SharePoint 2013 management interface using a user account that is a member of the administrators of the target machine, as well as a user that has been configured as a shell admin for SharePoint, using the Add-SPShellAdmin command.

  2. Verify that the User Profile service is installed and at least started on one of the application servers in the farm.

  3. Verify that the App Management service is installed and started in the current farm.

  4. Create or obtain the .cer file corresponding to the X.509 certificate you want to use for the high-trust configuration between SharePoint 2013 and the external app.

  5. If you want to manually generate the certificate from scratch, you can use the following syntax:

    makecert.exe -r -pe -n "CN={Name}" -b {StartDate} -e {EndData} -ss my
        -sr localMachine -sky exchange
        -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 file.cer

    where the -r argument instructs the tool to create a self-signed certificate. The -pe argument marks the private key as exportable. The -b and -e arguments define the start and end dates of validity of the target certificate. The -ss and -sr arguments specify storing the certificate in the personal store of the local machine. The -sky argument with a value of exchange instructs the tool to create a certificate with message-exchange capabilities (signature and encryption). Last, the -sp and -sy arguments declare the kind of CryptoAPI provider that will be used. If you want, you can also use IIS for creating a self-signed certificate, instead of using the makecert command-line tool.

  6. Start the SharePoint management shell or the Windows PowerShell ISE, and import the SharePoint 2013 cmdlets.

  7. Load the .cer file related to the X.509 certificate that you will use for the high-trust scenario and invoke the following cmdlet:

    $certificate = New-Object
        System.Security.Cryptography.X509Certificates.X509Certificate2(
        "{CERFilePath}")

    {CERFilePath} is the path of the .cer file related to the X.509 certificate file to use.

  8. Execute the following PowerShell commands:

    $appId = "{AppID}"
    $spweb = Get-SPWeb "{AppURL}"
    $realm = Get-SPAuthenticationRealm -ServiceContext $spweb.Site
    $fullAppIdentifier = $appId + '@' + $realm
    New-SPTrustedSecurityTokenIssuer -Name "{FriendlyName}"
    -Certificate $certificate -RegisteredIssuerName $fullAppIdentifier

    The {AppID} argument is the lowercase ID that identifies the app to trust, and it can be read from the app creation wizard when you create a new provider-hosted app. The {AppURL} argument is the URL of the app on the target server. {FriendlyName} is a friendly name that will be used to identify the high-trust relationship.

  9. Register the app within the App Management service by using the following PowerShell command:

    $appPrincipal = Register-SPAppPrincipal -NameIdentifier
        $fullAppIdentifier -Site $spweb -DisplayName "{DisplayName}"

    {DisplayName} will be the name representing the high-trust app in SPCA.

  10. Configure explicit permission for the target app, using the following cmdlet:

    Set-AppPrincipalPermission -appPrincipal $appPrincipal -site $web
        -right {Level} -scope {Scope}
  11. The arguments {Level} and {Scope} define the permissions exactly as you saw them in Chapter 8, in the section “The Permissions tab.”

After completing these steps, you will be ready to execute you SharePoint app, which will be a provider-hosted app running in an on-premises environment. Every authentication and authorization request between SharePoint 2013 and the app configured as high trust will be based on the just-defined X.509 certificate.

Summary

In this chapter, you learned about claims-based environments, WS-Federation, and how to use WIF to develop an IP/STS for a custom IP. You also saw how to register an IP/STS implemented with WIF into SharePoint for the purpose of authenticating SharePoint users through an external and trusted IP. Then you learned how to use Windows Azure ACS as an option for using an external IP/STS as a service. Lastly, the chapter discussed how SharePoint 2013 takes advantage of OAuth and S2S security while authenticating and authorizing SharePoint apps.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset