다음을 통해 공유


Microsoft Dynamics CRM Online 웹 서비스를 사용하여 Office 365 사용자 인증

 

게시 날짜: 2016년 11월

적용 대상: Dynamics CRM 2015

이 항목은 Microsoft Online Services 환경을 통해 Microsoft Dynamics CRM Online에 액세스하는 고객에게 적용됩니다. 조직 또는 검색 웹 서비스에 연결하는 응용 프로그램을 개발할 때 고려해야 하는 여러 개의 Microsoft Dynamics CRM Online ID 공급자가 있습니다. 이러한 공급자는 관리되는 도메인, 페더레이션 및 Microsoft 계정로 식별할 수 있습니다. 이 항목은 여기에 표시된 동일한 클래스와 코드가 지원되는 모든 ID 공급자 및 Microsoft Dynamics 365 배포 유형에도 작동하지만 관리되는 도메인과 페더레이션 ID 공급자와 함께 Microsoft Dynamics CRM Online 웹 서비스 인증에 초점을 맞추고 있습니다.

이 항목의 내용

간단한 인증 클래스 사용

Office 365로 Microsoft 계정 사용자 인증

인증 심층 이해

간단한 인증 클래스 사용

웹 서비스로 인증할 때 OrganizationServiceProxyDiscoveryServiceProxy 클래스를 사용할 수 있습니다. 이러한 프록시 클래스 사용에 대한 자세한 내용은 클라이언트 프록시 클래스를 사용하여 인증을 참조하십시오.

다른 인증 방법은 CrmConnection 클래스를 사용합니다. 몇 줄의 코드로 응용 프로그램을 웹 서비스로 인증하고 웹 메서드 호출을 시작할 수 있습니다.CrmConnection 클래스에 대한 자세한 내용은 Microsoft Dynamics CRM 2015에 대한 간단한 연결을 참조하십시오. 샘플 코드는 샘플: Microsoft Dynamics CRM을 사용하여 간소화된 연결 빠른 시작 항목에서 사용할 수 있습니다.

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

또 다른 인증 방법은 SDK에서 제공하는 도우미 원본 코드를 사용하는 것입니다.도우미 코드: ServerConnection 클래스 항목에 표시된 ServerConnection 도우미 클래스는 GetOrganizationProxyGetProxy 메서드를 인증에 사용합니다.ServerConnection의 원본 코드를 보면 GetOrganizationProxy에서 실제로 GetProxy를 호출합니다.

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

using 문에서 이러한 조직 또는 검색 서비스 프록시 개체를 만들어 서비스 프록시를 제대로 삭제하거나 Dispose를 직접 호출해야 합니다.GetOrganizationProxy 도우미 코드 메서드를 사용하는 샘플 코드는 샘플: Microsoft Dynamics CRM용 빠른 시작을 참조하십시오.

Microsoft Dynamics CRM SDK에서 사용할 수 있는 전체 인증 클래스 목록은 인증 클래스 섹션에 나와 있습니다.

Office 365로 Microsoft 계정 사용자 인증

응용 프로그램은 사용자의 조직이 Microsoft 계정 ID 공급자에서 Microsoft Online Services ID 공급자로 전환되는 Microsoft Dynamics CRM Online 사용자를 지원해야 합니다. 이 시나리오에서 사용자는 Microsoft Dynamics CRM Online의 Microsoft Online Services ID 공급자로 인증할 때 Microsoft 계정 로그온 자격 증명을 제공할 수 있습니다.

이렇게 하려면 OrganizationServiceProxy 생성자 또는 IServiceManagement 클래스의 Authenticate 메서드에서 입력된 로그온 자격 증명을 전달합니다. 자격 증명 값은 다음과 같이 입력됩니다.

AuthenticationCredentials.ClientCredentials = <Microsoft account logon credentials>
AuthenticationCredentials.SupportingCredentials.ClientCredentials = <device credentials>

DeviceIdManager 도우미 코드의 LoadOrRegister와 같은 공용 메서드 중 하나를 사용하여 장치 자격 증명을 얻을 수 있습니다. 자세한 내용은 도우미 코드: DeviceIdManager 클래스를 참조하십시오.

코드에서 ID 공급자 유형을 확인하여 인증 방법을 결정한 후 추가 코드가 필요합니다. 전환된 Microsoft 계정 사용자를 지원하는 샘플 코드에 대한 다음 섹션에서 GetCredentials 메서드를 참조하십시오.

이 전환에 대한 자세한 내용은 Office 365와 Microsoft Dynamics CRM Online 통합을 참조하십시오.

인증 심층 이해

앞에서 Microsoft Dynamics 365 웹 서비스로 사용자를 인증하는 데 사용할 수 있는 두 가지 간단한 방법을 소개했습니다. 다음 정보는 IServiceManagement<TService> 클래스를 사용하여 사용자를 인증하는 방법을 표시하고 GetProxy 메서드에 대한 원본 코드를 포함합니다. 다음 예제를 포함하는 전체 샘플을 보려면 샘플: Microsoft Dynamics CRM 웹 서비스를 사용하여 사용자 인증을 참조하십시오. 이 수준의 인증에는 더 많은 코드를 사용합니다.

다음 샘플 코드는 Microsoft Dynamics CRM Online 웹 서비스를 사용하여 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로 전달되어 웹 서비스 프록시 참조를 얻습니다.


/// <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 CRM Online에 연결
Microsoft Dynamics CRM Online 및 Office 365의 동기화된 사용자
샘플: Microsoft Dynamics CRM 웹 서비스를 사용하여 사용자 인증
도우미 코드: ServerConnection 클래스
Active Directory 및 클레임 기반 인증
Microsoft Dynamics CRM 2015에 대한 간단한 연결

© 2017 Microsoft. All rights reserved. 저작권 정보