How to: Use ACS Management Service to Configure Facebook as an Internet Identity Provider

Updated: June 19, 2015

Applies To: Azure

Applies To

  • Microsoft® Azure™ Access Control Service (ACS)

  • Facebook

Summary

This topic outlines the basic steps required for adding Facebook as an identity provider. Facebook can be added as an identity provider to ACS using the Management Portal or it can be automated with the ACS Management Service. Working with the Management Service is useful, for example, in scenarios when you are building a custom user interface for managing ACS or when automating the onboarding of a new tenant for multi-tenant Software as a Service (SaaS) solutions.

Contents

  • Objectives

  • Overview

  • Summary of Steps

  • Step 1 – Collect Configuration Information

  • Step 2 – Add References to the Required Services and Assemblies

  • Step 3 – Implement the Management Service Proxy

  • Step 4 – Add an Identity Provider

  • Step 5 – Test Your Work

Objectives

  • Identify the required prerequisites and configuration information.

  • List the steps required to add Facebook as an identity provider.

  • Test that the configuration is successful.

Overview

Management Service is a web service that is one of the key components of ACS. The Management Service exposes functionality that is available via the Management Portal user interface. Anything that can be accomplished in the Management Portal can also be done using the Management Service. Adding Facebook as an identity provider to ACS allows you to save on developing and maintaining the identity management mechanism of Internet scale. To accomplish the task of configuring Facebook as identity provider, you need to write code that follows specific steps. This topic outlines these basic steps.

Summary of Steps

  • Step 1 – Collect Configuration Information

  • Step 2 – Add References to the Required Services and Assemblies

  • Step 3 – Implement the Management Service Proxy

  • Step 4 – Add an Identity Provider

  • Step 5 – Test Your Work

Step 1 – Collect Configuration Information

This step identifies and shows how to collect the required configuration information. You need to collect the following information:

  • Management Service identity usernameManagementClient.

  • Management Service identity password—To obtain the service identity password for the management service:

    1. Log on to the Access Control Service Management Portal.

    2. In the Administration section, click the Management Service link.

    3. On the Management Service page, click the ManagementClient link (ManagementClient is the actual username for the service).

    4. In the Credentials section, click either the Symmetric Key or the Password link. The value in each is the same. This is the password.

  • Your service’s namespace

  • ACS hostname—Usually accesscontrol.windows.net.

  • Facebook Application ID and Application Secret—Follow the instructions in How to: Configure Facebook as an Identity Provider.

After collecting the required information, follow these steps to create a sample console application that will run the code for adding Facebook as an identity provider:

  1. Open Visual Studio® 2010 and create a new console application project.

  2. In the Program class, assign the information collected earlier to the module scope variables, using code similar to the following.

static string serviceIdentityUsernameForManagement = "ManagementClient";
static string serviceIdentityPasswordForManagement = "My Password for my ManagementClient";

static string serviceNamespace = "MyNameSpaceNoDots";
static string acsHostName = "accesscontrol.windows.net";
static string acsManagementServicesRelativeUrl = "v2/mgmt/service/";


static string cachedSwtToken;
static string identityProviderName = "Facebook";

static string facebookAppId = "Your Facebook AppID";
static string facebookAppSecret = "Your Facebook Secret";

Step 2 – Add References to the Required Services and Assemblies

This step identifies and adds the required dependencies to the services and assemblies.

To add the required dependencies to the services and assemblies

  1. Add a reference to System.Web.Extensions.

  2. Add a service reference to the Management Service. The Management Service URL is unique to your namespace and looks similar to the following:

    https://YOURNAMESPACE.accesscontrol.windows.net/v2/mgmt/service

  3. Add the following declarations.

    using System.Web; 
    using System.Net; 
    using System.Data.Services.Client; 
    using System.Collections.Specialized; 
    using System.Web.Script.Serialization;
    using System.Globalization;
    using System.Runtime.Serialization.Json;
    using ConsoleApplication1.ServiceReference1;
    

Notice the last declaration, ConsoleApplication1.ServiceReference1, it may vary in your case if you changed default values when creating your console application or when adding the reference to the management service.

Step 3 – Implement the Management Service Proxy

This step creates a method that encapsulates the implementation of the Management Service proxy.

To implement the Management Service proxy

  1. Add the following method to the Program class.

    public static ManagementService CreateManagementServiceClient()
            {
                string managementServiceEndpoint = String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/{2}",
                    serviceNamespace,
                    acsHostName,
                    acsManagementServicesRelativeUrl);
                ManagementService managementService = new ManagementService(new Uri(managementServiceEndpoint));
    
                managementService.SendingRequest += GetTokenWithWritePermission;
    
                return managementService;
            }
    
  2. Implement the GetTokenWithWritePermission method and its helper methods. It will add the SWT OAuth token to the Authorization header of the HTTP request.

    public static void GetTokenWithWritePermission(object sender, SendingRequestEventArgs args)
            {
                GetTokenWithWritePermission((HttpWebRequest)args.Request);
            }
    
            public static void GetTokenWithWritePermission(HttpWebRequest args)
            {
                if (cachedSwtToken == null)
                {
                    cachedSwtToken = GetTokenFromACS();
                }
    
                args.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + cachedSwtToken);
            }
    
            private static string GetTokenFromACS()
            {
                //
                // Request a token from ACS
                //
                WebClient client = new WebClient();
                client.BaseAddress = string.Format(CultureInfo.CurrentCulture, 
                                                   "https://{0}.{1}", 
                                                   serviceNamespace, 
                                                   acsHostName);
    
                NameValueCollection values = new NameValueCollection();
                values.Add("grant_type", "client_credentials");
                values.Add("client_id", serviceIdentityUsernameForManagement);
                values.Add("client_secret", serviceIdentityPasswordForManagement);
                values.Add("scope", client.BaseAddress + acsManagementServicesRelativeUrl);
    
                byte[] responseBytes = client.UploadValues("/v2/OAuth2-13", "POST", values);
    
                string response = Encoding.UTF8.GetString(responseBytes);
    
                // Parse the JSON response and return the access token 
                JavaScriptSerializer serializer = new JavaScriptSerializer();
    
                Dictionary<string, object> decodedDictionary = serializer.DeserializeObject(response) as Dictionary<string, object>;
    
                return decodedDictionary["access_token"] as string;
    
            }
    
    

Step 4 – Add an Identity Provider

This step adds Facebook as an identity provider using the Management Service proxy you created earlier.

To add Facebook as an identity provider

  1. In the Main method initialize the Management Service proxy.

    ManagementService svc = CreateManagementServiceClient();
    
  2. Add your identity provider as the issuer.

    Issuer issuer = new Issuer
    {
       Name = identityProviderName + “-” + facebookAppId
    };
    svc.AddToIssuers(issuer);
    svc.SaveChanges(SaveChangesOptions.Batch);
    
  3. Create an identity provider.

    var facebook = new IdentityProvider
    {
        DisplayName = identityProviderName,
        LoginLinkName = "Facebook",
        LoginParameters = "email",
        WebSSOProtocolType = "Facebook",
        IssuerId = issuer.Id
    };
    
    svc.AddObject("IdentityProviders", facebook);
    
  4. Create an identity provider signing key based on the certificate you obtained earlier.

    var facebookKeys = new[]
        {
            new IdentityProviderKey
                {
                    IdentityProvider = facebook,
                    StartDate = DateTime.UtcNow,
                    EndDate = DateTime.UtcNow.AddYears(1),
                    Type = "ApplicationKey",
                    Usage = "ApplicationId",
                    Value = Encoding.UTF8.GetBytes(facebookAppId)
                },
            new IdentityProviderKey
                {
                    IdentityProvider = facebook,
                    StartDate = DateTime.UtcNow,
                    EndDate = DateTime.UtcNow.AddYears(1),
                    Type = "ApplicationKey",
                    Usage = "ApplicationSecret",
                    Value = Encoding.UTF8.GetBytes(facebookAppSecret)
                }
        };
    
    foreach (var key in facebookKeys)
    {
        svc.AddRelatedObject(facebook, "IdentityProviderKeys", key);
    }
    
    svc.SaveChanges(SaveChangesOptions.Batch);
    
  5. Make the identity provider available to relying parties, except the Management Service.

    foreach (RelyingParty rp in svc.RelyingParties)
    {
        // skip the built-in management RP. 
        if (rp.Name != "AccessControlManagement")
        {
            svc.AddToRelyingPartyIdentityProviders(new RelyingPartyIdentityProvider()
            {
                IdentityProviderId = facebook.Id,
                RelyingPartyId = rp.Id
            });
        }
    }
    
    svc.SaveChanges(SaveChangesOptions.Batch);
    

Step 5 – Test Your Work

To test your work

  1. Log on to the Access Control Service Management Portal.

  2. On the Access Control Service page, click the Rule Groups link in the Trust Relationships section.

  3. Click any of the available rules.

  4. On the Edit Rule Group page, click the Add Rule link.

  5. On the Add Claim Rule page, choose the newly added identity provider from the drop-down list in the Claim Issuer section.

  6. Leave the rest of the default values.

  7. Click Save.

You have just created a pass-through rule for the identity provider.