Esporta (0) Stampa
Espandi tutto
EN
Il contenuto non è disponibile nella lingua di destinazione, ma solo in inglese.
Questo argomento non è stato ancora valutato - Valuta questo argomento

How to: Use ACS Management Service to Configure Service Identities

Published: April 7, 2011

Updated: February 21, 2014

Applies To: Windows Azure

Applies To

  • Windows Azure Active Directory Access Control (also known as Access Control Service or ACS)

Overview

You can configure ACS service identities using either the ACS Management Portal (for more information, see Service Identities) or the ACS Management Service. Working with the ACS Management Service can be more efficient if you are building a custom user interface for managing ACS or if you want to automate the onboarding of a new tenant for multi-tenant Software as a Service (SaaS) solutions.

Steps for Configuring Service Identities Using the ACS Management Service

ImportantImportant
Before performing the following steps, make sure that your system meets all of the .NET framework and platform requirements that are summarized in ACS Prerequisites.

To configure service identities using the ACS Management Service, complete the following steps:

Step 1 – Collect ACS Configuration Information

You can use the ACS Management Portal to collect the necessary configuration information. For more information about how to launch the ACS Management Portal, see ACS Management Portal.

To collect ACS configuration information

  1. Launch the ACS Management Portal. For more information about how to launch the ACS Management Portal, see ACS Management Portal.

  2. Obtain the value of the ACS management service account. You can use the default ManagementClient account. To view this value, in the ACS Management Portal, click Management service under the Administration section in the tree on the left-hand side of the page.

  3. Obtain the value of the ACS Management Service account password. To view this value, do the following:

    1. In the ACS Management Portal, click Management service under the Administration section in the tree on the left-hand side of the page.

    2. On the Management Service page, click ManagementClient under Management Service Accounts.

    3. On the Edit Management Service Account page, under Credentials, click Password.

    4. On the Edit Management Credential page, copy the value in the Password field.

  4. Obtain the value of your Windows Azure namespace. You can obtain this value from the Windows Azure portal or from the URL of your ACS Management Portal. For example, in http://contoso.accesscontrol.windows.net, the value of the Windows Azure namespace is contoso.

  5. Obtain the value of the ACS hostname. Usually, it is accesscontrol.windows.net.

Step 2 – Create a sample console application

In this step you create a sample console application that can run the code for adding your ACS service identities.

To create a sample console application

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

  2. Add the following code to the Program class and then assign serviceIdentityPasswordForManagement, serviceNamespace, and acsHostName variables to the appropriate configuration information that you collected in the step above.

    public const string serviceIdentityUsernameForManagement = "ManagementClient";
    public const string serviceIdentityPasswordForManagement = "My Password/Key for ManagementClient";
    public const string serviceNamespace = "MyNameSpaceNoDots";
    public const string acsHostName = "accesscontrol.windows.net";
    public const string acsManagementServicesRelativeUrl = "v2/mgmt/service/";
    static string cachedSwtToken;
    
    

Step 3 – Add References to the Required Services and Assemblies

In this step you identify and add the required dependencies to the services and assemblies.

To add the required dependencies to the services and assemblies

  1. Right-click References, click Add Reference, and add a reference to System.Web.Extensions.

    noteNote
    You might have to right-click your sample console application name in the Solution Explorer, select Properties, and change the target framework of your sample application from .NET Framework 4 Client Profile (assigned by default when you create a new console application) to .NET Framework 4.

  2. Right-click Service References, click Add Service Reference, and 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, where MyConsoleApplication is the name of your console application and MyServiceReference is the name of your service reference:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    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.Security.Cryptography;
    using System.Security.Cryptography.X509Certificates;
    using MyConsoleApplication.MyServiceReference;
    
    

Step 4 – Implement the Management Service Client

In this step you implement the Management Service client.

To implement the Management Service client

  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. Add the following code to the Program class to create GetTokenWithWritePermission method and its helper methods. GetTokenWithWritePermission and its helpers 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 5 – Add a Service Identity

In this step you add a service identity using the Management Service client you created in the step above. ACS service identity can use a password, a symmetric key, or an X.509 certificate as a credential type.

To add a service identity

  1. Initialize the Management Service client by adding the following code to the Main method in the Program class:

    ManagementService svc = CreateManagementServiceClient();
    
    
  2. Do one of the following:

    • To add a service identity associated with a password and save changes, add the following code to the Main method in the Program class:

      noteNote
      You can call this service identity “SampleServiceIdentity” and set its password to “SampleServiceIdentityPassword” as shown in the code below.

      
                  string name = "SampleServiceIdentity";
                  string password = "SampleServiceIdentityPassword";
                  ServiceIdentity sid = new ServiceIdentity()
                  {
                      Name = name
                  };
      
                  DateTime startDate, endDate;
                  startDate = DateTime.UtcNow;
                  endDate = DateTime.MaxValue;
      
                  ServiceIdentityKey key = new ServiceIdentityKey()
                  {
                      EndDate = endDate.ToUniversalTime(),
                      StartDate = startDate.ToUniversalTime(),
                      Type = "Password",
                      Usage = "Password",
                      Value = Encoding.UTF8.GetBytes(password),
                      DisplayName = String.Format(CultureInfo.InvariantCulture, "{0} key for {1}", "Password", name)
                  };
      
                  svc.AddToServiceIdentities(sid);
                  svc.AddRelatedObject(
                      sid,
                      "ServiceIdentityKeys",
                      key);
      
      
                  svc.SaveChanges(SaveChangesOptions.Batch);
      
      
    • To add a service identity associated with a symmetric key and save changes, add the following code to the Main method in the Program class:

      noteNote
      You can call this service identity “SampleServiceIdentity” and set its symmetric key value to “SampleServiceIdentityPassword” as shown in the code below.

      
                  string name = "SampleServiceIdentity";
                  string symKey = "SampleServiceIdentitySymmetricKey";
                  ServiceIdentity sid = new ServiceIdentity()
                  {
                      Name = name
                  };
      
                  DateTime startDate, endDate;
                  startDate = DateTime.UtcNow;
                  endDate = DateTime.MaxValue;
      
                  ServiceIdentityKey key = new ServiceIdentityKey()
                  {
                      EndDate = endDate.ToUniversalTime(),
                      StartDate = startDate.ToUniversalTime(),
                      Type = "Symmetric",
                      Usage = "Signing",
                      Value = Convert.FromBase64String(symKey),
                      DisplayName = String.Format(CultureInfo.InvariantCulture, "{0} key for {1}", "Sym Key", name)
                  };
      
                  svc.AddToServiceIdentities(sid);
                  svc.AddRelatedObject(
                      sid,
                      "ServiceIdentityKeys",
                      key);
      
      
                  svc.SaveChanges(SaveChangesOptions.Batch);
      
      
    • To add a service identity associated with an X.509 certificate and save changes, add the following code to the Main method in the Program class:

      noteNote
      You can call this service identity “SampleServiceIdentity” as shown in the code below

      In the code below, replace "Full path to your .CER file" with the fully qualified path to your X.509 certificate. For example, if a certificate called ACS2ClientCertificate.cer is saved in C:\, the correct value is "C:\ ACS2ClientCertificate.cer".

      
                  string name = "SampleServiceIdentity";
                  X509Certificate2 cert = new X509Certificate2(@"Full path to your .CER file");
      
                  ServiceIdentity sid = new ServiceIdentity()
                  {
                      Name = name
                  };
      
                  DateTime startDate, endDate;
      
                  startDate = cert.NotBefore.ToUniversalTime();
                  endDate = cert.NotAfter.ToUniversalTime();
      
                  ServiceIdentityKey key = new ServiceIdentityKey()
                  {
                      EndDate = endDate.ToUniversalTime(),
                      StartDate = startDate.ToUniversalTime(),
                      Type = "X509Certificate",
                      Usage = "Signing",
                      Value = cert.GetRawCertData(),
                      DisplayName = String.Format(CultureInfo.InvariantCulture, "{0} key for {1}", "Cert", name)
                  };
      
                  svc.AddToServiceIdentities(sid);
                  svc.AddRelatedObject(
                      sid,
                      "ServiceIdentityKeys",
                      key);
      
      
                  svc.SaveChanges(SaveChangesOptions.Batch);
      
      

See Also

Concepts

ACS How To's

Aggiunte alla community

AGGIUNGI
Mostra:
© 2014 Microsoft. Tutti i diritti riservati.