Microsoft Dynamics 365 (オンライン) Web サービスで Office 365 ユーザーを認証する

 

公開日: 2017年1月

対象: Dynamics 365 (online)、Dynamics 365 (on-premises)、Dynamics CRM 2016、Dynamics CRM Online

このトピックは、Microsoft Online Services 環境 を通して Microsoft Dynamics 365 (オンライン) にアクセスする顧客に適用されます。 組織 Web サービスまたは検索 Web サービスに接続するアプリケーションを開発するときに考慮にいれる Microsoft Dynamics 365 (オンライン) 複数の ID プロバイダーがあります。 これらのプロバイダは管理フェデレーション ドメインおよび Microsoft アカウント として識別されます。 次に示す同じクラスとコードが、すべてのサポートされる ID プロバイダーと Microsoft Dynamics 365 展開の種類で動作しますが、このトピックでは、管理ドメインとフェデレーション ID プロバイダーでの Microsoft Dynamics 365 (オンライン) Web サービスの認証について焦点を当てています。

このトピックの内容

簡素化された認定クラスを使用する

Office 365 を使用して Microsoft アカウント ユーザーを認証する

より複雑な認証

簡素化された認定クラスを使用する

OrganizationServiceProxyDiscoveryServiceProxy クラスを Web サービスの認証に使用できます。 これらのプロキシ クラスの使用に関する詳細については、「クライアント プロキシ クラスを使用した認証」を参照してください。

他の認証方法は CrmConnection クラスを使用します。 コードを数行使用することで、アプリケーションは Web メソッドを認証し、Web サービスの呼び出しを開始できます。CrmConnection クラスの詳細については、Microsoft Dynamics CRM へのより簡単な接続を参照してください。 サンプル コードは、サンプル: Microsoft Dynamics CRM を使用した単純化接続のクイック スタート に用意されています。

CrmConnection connection = CrmConnection.Parse (connectionString);
using ( OrganizationService orgService = new OrganizationService(connection)) { }

別の認証方法は、SDK で提供されるヘルパー ソース コードを使用することです。ヘルパー コード: ServerConnection クラス のトピックで示す ServerConnection のヘルパー クラスは、認証の GetOrganizationProxy および GetProxy メソッドを提供します。ServerConnectionのソース コードでは、実際には GetOrganizationProxyGetProxy を呼び出すします。

using ( OrganizationServiceProxy orgServiceProxy = ServerConnection.GetOrganizationProxy(serverConfig) ) { }

これらの組織または検索サービス プロキシ オブジェクトを using ステートメントに作成して、サービス プロキシを適切に破棄するか Dispose を直接呼び出す必要があります。GetOrganizationProxy のヘルパー コード メソッドを使用するサンプルについては、「サンプル: Microsoft Dynamics 365 のクイック スタート」を参照してください。

Microsoft Dynamics 365 SDK で入手できる認証クラスの一覧が、認証クラス "セクションに表示されます。

Office 365 を使用して Microsoft アカウント ユーザーを認証する

アプリケーションは、Microsoft アカウント の ID プロバイダーから Microsoft Online Services の ID プロバイダーに組織を移行した Microsoft Dynamics 365 (オンライン) のユーザーをサポートする必要があります。 このシナリオでは、ユーザーは Microsoft Dynamics 365 (オンライン)の Microsoft Online Services ID プロバイダーで認証を行う場合、Microsoft アカウント のサインイン資格情報を入力する場合があります。

これを行うには、OrganizationServiceProxy コンストラクターまたは IServiceManagement クラスのメソッド Authenticate の、設定済み資格情報を渡します。 資格情報の値は以下のように設定されます。

AuthenticationCredentials.ClientCredentials = <Microsoft account sign-in credentials>
AuthenticationCredentials.SupportingCredentials.ClientCredentials = <device credentials>

デバイスの資格情報は、たとえば DeviceIdManager ヘルパー コード内の LoadOrRegister などの、一般の方法のいずれかを使用して取得できます。 詳細については、「ヘルパー コード: DeviceIdManager クラス」を参照してください。

コードが ID プロバイダーの種類を確認して認証方法を決定する場合、追加のコードが必要です。 移行済みの Microsoft アカウント ユーザーをサポートするサンプル コードは、次のセクションの GetCredentials 方法を参照してください。

この以降の詳細情報は、Microsoft Dynamics 365 (オンライン) の Office 365 との統合を参照してください。

より複雑な認証

以前のトピックは、Microsoft Dynamics 365 Web サービスでユーザーを認証するために使用する 2 の簡単な方法を紹介しました。 次の情報は、IServiceManagement<TService> クラスを使用してユーザーを認証する方法を紹介し、GetProxy メソッドへのソース コードが含まれています。 次の例を含む完全なサンプルについては、「サンプル: Microsoft Dynamics 365Web サービスでユーザーを認証する」を参照してください。 このレベル認証は、もっと多くのコードが必要です。

次のサンプル コードは、Microsoft Dynamics 365 (オンライン) Web サービスを使用する Office 365/MOS のユーザーを認証するためにアプリケーションで使用できるメソッドおよびクラスを示しています。


IServiceManagement<IOrganizationService> orgServiceManagement =
    ServiceConfigurationFactory.CreateManagement<IOrganizationService>(
    new Uri(organizationUri));

// Set the credentials.
AuthenticationCredentials credentials = GetCredentials(orgServiceManagement, endpointType);

// Get the organization service proxy.
using (OrganizationServiceProxy organizationProxy =
    GetProxy<IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, credentials))
{
    // This statement is required to enable early-bound type support.
    organizationProxy.EnableProxyTypes();

    // Now make an SDK call with the organization service proxy.
    // Display information about the logged on user.
    Guid userid = ((WhoAmIResponse)organizationProxy.Execute(
        new WhoAmIRequest())).UserId;
    SystemUser systemUser = organizationProxy.Retrieve("systemuser", userid,
        new ColumnSet(new string[] { "firstname", "lastname" })).ToEntity<SystemUser>();
    Console.WriteLine("Logged on user is {0} {1}.",
        systemUser.FirstName, systemUser.LastName);
}

Dim orgServiceManagement As IServiceManagement(Of IOrganizationService) =
    ServiceConfigurationFactory.CreateManagement(Of IOrganizationService)(New Uri(organizationUri))

' Set the credentials.
Dim credentials As AuthenticationCredentials = GetCredentials(endpointType_renamed)

' Get the organization service proxy.
Using organizationProxy As OrganizationServiceProxy =
    GetProxy(Of IOrganizationService, OrganizationServiceProxy)(orgServiceManagement, credentials)
    ' This statement is required to enable early-bound type support.
    organizationProxy.EnableProxyTypes()

    ' Now make an SDK call with the organization service proxy.
    ' Display information about the logged on user.
    Dim userid As Guid = (CType(organizationProxy.Execute(New WhoAmIRequest()), 
                          WhoAmIResponse)).UserId
    Dim systemUser_renamed As SystemUser =
        organizationProxy.Retrieve("systemuser",
                                   userid,
                                   New ColumnSet(New String() {"firstname",
                                                               "lastname"})).ToEntity(Of SystemUser)()
    Console.WriteLine("Logged on user is {0} {1}.",
                      systemUser_renamed.FirstName, systemUser_renamed.LastName)
End Using

コードは、組織サービスの IServiceManagement<TService> オブジェクトを作成します。AuthenticationCredentials の種類のオブジェクトが、ユーザーのサインイン資格情報を格納するために使用されます。IServiceManagement オブジェクトおよびユーザーの資格情報は GetProxy に渡され、Web サービス プロキシの参照を取得します。


/// <summary>
/// Obtain the AuthenticationCredentials based on AuthenticationProviderType.
/// </summary>
/// <param name="service">A service management object.</param>
/// <param name="endpointType">An AuthenticationProviderType of the CRM environment.</param>
/// <returns>Get filled credentials.</returns>
private AuthenticationCredentials GetCredentials<TService>(IServiceManagement<TService> service, AuthenticationProviderType endpointType)
{
    AuthenticationCredentials authCredentials = new AuthenticationCredentials();

    switch (endpointType)
    {
        case AuthenticationProviderType.ActiveDirectory:
            authCredentials.ClientCredentials.Windows.ClientCredential =
                new System.Net.NetworkCredential(_userName,
                    _password,
                    _domain);
            break;
        case AuthenticationProviderType.LiveId:
            authCredentials.ClientCredentials.UserName.UserName = _userName;
            authCredentials.ClientCredentials.UserName.Password = _password;
            authCredentials.SupportingCredentials = new AuthenticationCredentials();
            authCredentials.SupportingCredentials.ClientCredentials =
                Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice();
            break;
        default: // For Federated and OnlineFederated environments.                    
            authCredentials.ClientCredentials.UserName.UserName = _userName;
            authCredentials.ClientCredentials.UserName.Password = _password;
            // For OnlineFederated single-sign on, you could just use current UserPrincipalName instead of passing user name and password.
            // authCredentials.UserPrincipalName = UserPrincipal.Current.UserPrincipalName;  // Windows Kerberos

            // The service is configured for User Id authentication, but the user might provide Microsoft
            // account credentials. If so, the supporting credentials must contain the device credentials.
            if (endpointType == AuthenticationProviderType.OnlineFederation)
            {
                IdentityProvider provider = service.GetIdentityProvider(authCredentials.ClientCredentials.UserName.UserName);
                if (provider != null &amp;&amp; provider.IdentityProviderType == IdentityProviderType.LiveId)
                {
                    authCredentials.SupportingCredentials = new AuthenticationCredentials();
                    authCredentials.SupportingCredentials.ClientCredentials =
                        Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice();
                }
            }

            break;
    }

    return authCredentials;
}

''' <summary>
''' Obtain the AuthenticationCredentials based on AuthenticationProviderType.
''' </summary>
''' <param name="endpointType">An AuthenticationProviderType of the CRM environment.</param>
''' <returns>Get filled credentials.</returns>
Private Function GetCredentials(ByVal endpointType As AuthenticationProviderType) As AuthenticationCredentials

    Dim authCredentials As New AuthenticationCredentials()
    Select Case endpointType
        Case AuthenticationProviderType.ActiveDirectory
                  authCredentials.ClientCredentials.Windows.ClientCredential =
                      New System.Net.NetworkCredential(_userName, _password, _domain)
        Case AuthenticationProviderType.LiveId
            authCredentials.ClientCredentials.UserName.UserName = _userName
            authCredentials.ClientCredentials.UserName.Password = _password
            authCredentials.SupportingCredentials = New AuthenticationCredentials()
                  authCredentials.SupportingCredentials.ClientCredentials =
                      Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice()
        Case Else ' For Federated and OnlineFederated environments.
            authCredentials.ClientCredentials.UserName.UserName = _userName
            authCredentials.ClientCredentials.UserName.Password = _password
            ' For OnlineFederated single-sign on, you could just use current UserPrincipalName instead of passing user name and password.
            ' authCredentials.UserPrincipalName = UserPrincipal.Current.UserPrincipalName;  //Windows/Kerberos
    End Select

    Return authCredentials
End Function

AuthenticationCredentials オブジェクトは、サインインしたユーザーのサブスクライブ ID に基づいて構成されます。 すべての種類の ID プロバイダーに対するユーザーの資格情報が表示されることに注意してください。 既定のケースでは、Microsoft Office 365/MOS 管理ドメイン、ID がクラウド フェデレーションされるオンライン ユーザー、および移行済み Microsoft アカウント のユーザーを処理します。GetProxy の実際の働きを以下に示します。


private TProxy GetProxy<TService, TProxy>(
    IServiceManagement<TService> serviceManagement,
    AuthenticationCredentials authCredentials)
    where TService : class
    where TProxy : ServiceProxy<TService>
{
    Type classType = typeof(TProxy);

    if (serviceManagement.AuthenticationType !=
        AuthenticationProviderType.ActiveDirectory)
    {
        AuthenticationCredentials tokenCredentials =
            serviceManagement.Authenticate(authCredentials);
        // Obtain discovery/organization service proxy for Federated, LiveId and OnlineFederated environments. 
        // Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and SecurityTokenResponse.
        return (TProxy)classType
            .GetConstructor(new Type[] { typeof(IServiceManagement<TService>), typeof(SecurityTokenResponse) })
            .Invoke(new object[] { serviceManagement, tokenCredentials.SecurityTokenResponse });
    }

    // Obtain discovery/organization service proxy for ActiveDirectory environment.
    // Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and ClientCredentials.
    return (TProxy)classType
        .GetConstructor(new Type[] { typeof(IServiceManagement<TService>), typeof(ClientCredentials) })
        .Invoke(new object[] { serviceManagement, authCredentials.ClientCredentials });
}

Private Function GetProxy(Of TService As Class,
                              TProxy As ServiceProxy(Of TService)) _
                          (ByVal serviceManagement As IServiceManagement(Of TService),
                           ByVal authCredentials As AuthenticationCredentials) As TProxy
    Dim classType As Type = GetType(TProxy)

    If serviceManagement.AuthenticationType <>
        AuthenticationProviderType.ActiveDirectory Then
        Dim tokenCredentials As AuthenticationCredentials =
            serviceManagement.Authenticate(authCredentials)
        ' Obtain discovery/organization service proxy for Federated, LiveId and OnlineFederated environments. 
        ' Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and SecurityTokenResponse.
        Return CType(classType _
        .GetConstructor(New Type() {GetType(IServiceManagement(Of TService)), GetType(SecurityTokenResponse)}) _
        .Invoke(New Object() {serviceManagement, tokenCredentials.SecurityTokenResponse}), TProxy)
    End If

    ' Obtain discovery/organization service proxy for ActiveDirectory environment.
    ' Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and ClientCredentials.
    Return CType(classType _
        .GetConstructor(New Type() {GetType(IServiceManagement(Of TService)), GetType(ClientCredentials)}) _
        .Invoke(New Object() {serviceManagement, authCredentials.ClientCredentials}), TProxy)
End Function

設置型 (要求なしの Active Directory) を以外のすべての展開で、Authenticate メソッドが起動され、サービス プロキシがインスタント化されます。Authenticate から返される認証資格情報は、サービス プロキシ コンストラクターで使用されるセキュリティ トークンの応答を含むことに注意してください。 前述した一般的な GetProxy メソッドを使用して、OrganizationServiceProxy または DiscoveryServiceProxy へのオブジェクト参照を取得できます。

関連項目

Microsoft Office 365 および Microsoft Dynamics 365 (オンライン) と接続する
Microsoft Dynamics 365 (オンライン) と Office 365 での同期されたユーザー
サンプル: Microsoft Dynamics 365Web サービスでユーザーを認証する
ヘルパー コード: ServerConnection クラス
Active Directory およびクレームベース認証
XRM ツールの接続文字列を使用して Dynamics 365に接続する

Microsoft Dynamics 365

© 2017 Microsoft. All rights reserved. 著作権