Autenticare gli utenti di Office 365 tramite i servizi Web di Microsoft Dynamics 365 (online)

 

Data di pubblicazione: gennaio 2017

Si applica a: Dynamics 365 (online), Dynamics 365 (on-premises), Dynamics CRM 2016, Dynamics CRM Online

Questo argomento si applica a clienti che accedono a Microsoft Dynamics 365 (online) tramite Ambiente dei Microsoft Online Services. Esistono più provider di identità di Microsoft Dynamics 365 (online) che devono essere presi in considerazione quando si sviluppa un'applicazione che si connette ai servizi Web di individuazione o dell'organizzazione. Tali provider possono essere identificati come dominio gestito, federato e Account Microsoft. Questo argomento è incentrato sull'autenticazione del servizio Web di Microsoft Dynamics 365 (online) con dominio gestito e provider di identità federati, anche se le stesse classi e codici qui visualizzati hanno un corretto funzionamento anche con tutti i provider di identità e tipi di distribuzione di Microsoft Dynamics 365 supportati.

In questo argomento

Utilizzare le classi di autenticazione semplificate

Autenticare gli utenti account Microsoft con Office 365

Dimostrazione dettagliata dell'autenticazione

Utilizzare le classi di autenticazione semplificate

È possibile utilizzare le classi DiscoveryServiceProxy e OrganizationServiceProxy quando si effettua l'autenticazione con i servizi Web. Per ulteriori informazioni sull'utilizzo di queste classi proxy, vedere Autenticazione tramite le classi proxy del client.

Un altro metodo di autenticazione utilizza la classe CrmConnection. Con poche righe di codice, l'applicazione può effettuare l'autenticazione con i servizi Web e iniziare a chiamare i metodi Web. Per ulteriori informazioni sulla classe CrmConnection, vedi Connessione semplificata a Microsoft Dynamics CRM. Il codice di esempio è disponibile nell'argomento Esempio: Avvio rapido semplificato di connessione con Microsoft Dynamics CRM

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

Un altro metodo di autenticazione consiste nell'utilizzare il codice sorgente fornito in SDK. La classe helper ServerConnection, illustrata nell'argomento Codice dell'helper: classe di ServerConnection fornisce i metodi di autenticazione GetOrganizationProxy e metodi GetProxy. Se si analizza il codice sorgente di ServerConnection, si nota che GetOrganizationProxy in realtà chiama GetProxy.

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

È necessario creare queste organizzazioni o oggetti proxy del servizio di individuazione in una dichiarazione using per eliminare correttamente il proxy del servizio o chiamare Dispose direttamente. Per il codice di esempio che utilizza il metodo di codice dell'helper GetOrganizationProxy, vedere Esempio - Guida introduttiva per Microsoft Dynamics 365.

L'elenco completo delle classi di autenticazione disponibili in Microsoft Dynamics 365 SDK è illustrato nella sezione Classi di autenticazione.

Autenticare gli utenti account Microsoft con Office 365

L'applicazione deve supportare gli utenti di Microsoft Dynamics 365 (online) per la cui organizzazione è eseguita la transizione dal provider di identità di Account Microsoft al provider di identità del Microsoft Online Services. In questo scenario, gli utenti possono specificare le proprie credenziali di accesso a Account Microsoft quando effettuano l'autenticazione con il provider di identità Microsoft Online Services di Microsoft Dynamics 365 (online).

A tale scopo, passare le credenziali di accesso popolate nel OrganizationServiceProxy del costruttore o il metodo Authenticate della classe IServiceManagement. I valori di credenziali sono popolati come segue:

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

È possibile ottenere le credenziali del dispositivo utilizzando uno dei metodi pubblici, ad esempio LoadOrRegister, nel codice dell'helper DeviceIdManager. Per ulteriori informazioni, vedere Codice dell'helper: classe DeviceIdManager.

Se il codice controlla il tipo del provider di identità per determinare come effettuare l'autenticazione, è necessario codice addizionale. Vedere il metodo GetCredentials nella sezione successiva per il codice di esempio che supporta gli utenti di Account Microsoft per i quali si effettua una transizione.

Per ulteriori informazioni su questa transizione, vedere Integrazione di Microsoft Dynamics 365 (online) con Office 365.

Dimostrazione dettagliata dell'autenticazione

La discussione precedente ha introdotto due semplici modi con i quali è possibile autenticare un utente con i servizi Web Microsoft Dynamics 365. Le informazioni riportate di seguito illustrano come autenticare un utente utilizzando la classe IServiceManagement<TService> e includono il codice sorgente del metodo GetProxy. Per visualizzare l'esempio completo che contiene gli esempi seguenti, vedere Esempio - Autenticare gli utenti tramite i servizi Web di Microsoft Dynamics 365. Notare che l'autenticazione a questo livello necessita di molto più codice.

Il seguente codice di esempio illustra classi e metodi utilizzabili nell'applicazione per autenticare un utente di Office 365/MOS tramite i servizi Web Microsoft Dynamics 365 (online).


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

Il codice crea un oggetto IServiceManagement<TService> per il servizio di organizzazione. Un oggetto di tipo AuthenticationCredentials viene utilizzato per contenere le credenziali di accesso dell'utente. L'oggetto IServiceManagement e le credenziali utente vengono quindi passati a GetProxy per ottenere i riferimenti del proxy dei servizi 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

L'oggetto AuthenticationCredentials è configurato in base all'identità sottoscritta per l'utente connesso. Si noti che le credenziali degli utenti per tutti i tipi di provider di identità vengono visualizzate. Il caso predefinito gestisce il dominio gestito Microsoft Office 365/MOS, gli utenti online le cui identità sono federate nel cloud e gli utenti di Account Microsoft per i quali è stata effettuata la transizione. Verranno ora esaminato l'effettivo comportamento di 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

Per tutte le distribuzioni diverse dalle locali (Active Directory, senza attestazioni), il metodo Authenticate viene invocato e viene creata l'istanza del proxy. Si noti che le credenziali di autenticazione restituite da Authenticate contengono la risposta del token di sicurezza utilizzato nel costruttore del proxy del servizio. Il metodo generico GetProxy indicato in precedenza può essere utilizzato per ottenere un riferimento dell'oggetto a OrganizationServiceProxy o DiscoveryServiceProxy.

Vedere anche

Connettersi con Microsoft Office 365 e Microsoft Dynamics 365 (online)
Utenti sincronizzati in Microsoft Dynamics 365 (online) e Office 365
Esempio - Autenticare gli utenti tramite i servizi Web di Microsoft Dynamics 365
Codice dell'helper: classe di ServerConnection
Active Directory e autenticazione basata sulle attestazioni
Utilizzare le stringhe di connessione negli strumenti XRM per connettersi a Dynamics 365

Microsoft Dynamics 365

© 2017 Microsoft. Tutti i diritti sono riservati. Copyright