从.Net访问Microsoft CRM Dynamics 365

时间:2016-12-21 09:49:52

标签: c# .net dynamics-crm-online dynamics-crm-365

我需要访问CRM Dynamics 365我使用下面的代码通过“ADFS(IFD)身份验证”访问其工作正常,但使用CRM Online“Dynamics 365 https://OrgName.api.crm4.dynamics.com/XRMServices/2011/Organization.svc

收到此错误:

从另一方收到了不安全或不正确的安全故障。请参阅内部FaultException以获取故障代码和详细信息。

Server stack trace: 
   at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
   at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]: 
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at System.ServiceModel.Security.IWSTrustContract.Issue(Message message)
   at System.ServiceModel.Security.WSTrustChannel.Issue(RequestSecurityToken rst, RequestSecurityTokenResponse& rstr)
   at Microsoft.Xrm.Sdk.Client.ServiceConfiguration`1.Issue(AuthenticationCredentials authenticationCredentials)
   at Microsoft.Xrm.Sdk.Client.ServiceConfiguration`1.AuthenticateInternal(AuthenticationCredentials authenticationCredentials)
   at Microsoft.Xrm.Sdk.Client.ServiceConfiguration`1.AuthenticateWithOrgIdForACS(AuthenticationCredentials authenticationCredentials, Uri identifier)
   at Microsoft.Xrm.Sdk.Client.ServiceConfiguration`1.AuthenticateOnlineFederationInternal(AuthenticationCredentials authenticationCredentials)
   at Microsoft.Xrm.Sdk.Client.ServiceConfiguration`1.Authenticate(AuthenticationCredentials authenticationCredentials)
   at Microsoft.Xrm.Sdk.Client.OrganizationServiceConfiguration.Authenticate(AuthenticationCredentials authenticationCredentials)

这是我的代码:

public static IOrganizationService GetService()
{

    try
    {
        OrganizationServiceProxy _serviceProxy;

        string userName = "";
        string password = "";
        string domain = "";
        Uri serviceUri;


        serviceUri = new Uri(ConfigurationManager.AppSettings["URL"]);
        userName = ConfigurationManager.AppSettings["UserName"];
        password = ConfigurationManager.AppSettings["Password"];
        domain = ConfigurationManager.AppSettings["domain"];


        IServiceManagement<IOrganizationService> orgServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(serviceUri);

        if (orgServiceManagement.AuthenticationType == AuthenticationProviderType.Federation)
        {
            // ADFS (IFD) Authentication
            ClientCredentials clientCred = new ClientCredentials();
            clientCred.UserName.UserName = userName;
            clientCred.UserName.Password = password;
            _serviceProxy = new OrganizationServiceProxy(orgServiceManagement, clientCred);
        }
        else if (orgServiceManagement.AuthenticationType == AuthenticationProviderType.OnlineFederation)
        {
            // Online authentication
            AuthenticationCredentials authCredentials = new AuthenticationCredentials();

            authCredentials.ClientCredentials.UserName.UserName = userName;
            authCredentials.ClientCredentials.UserName.Password = password;

            // Error getting here
            AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(authCredentials); 


            _serviceProxy = new OrganizationServiceProxy(orgServiceManagement, tokenCredentials.SecurityTokenResponse);
        }
        else
        {
            // On-Premise, non-IFD authentication
            ClientCredentials credentials = new ClientCredentials();
            credentials.Windows.ClientCredential = new NetworkCredential(userName, password, domain);
            _serviceProxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
        }

        _serviceProxy.EnableProxyTypes();


    }
    catch (Exception e)
    {

    }

    return (IOrganizationService)_serviceProxy;
}

3 个答案:

答案 0 :(得分:0)

尝试this文章中的修复:

要解决此问题,您可以尝试删除配置文件文件夹C:\ Users \中名为LiveDeviceID的设备注册文件夹。然后,再次尝试连接。

答案 1 :(得分:0)

通过在此Connect to CRM Online or On-premise

中使用此代码解决了问题

答案 2 :(得分:0)

这可能是原因:

  1. Microsoft已弃用Azure访问控制服务(ACS)
  2. Microsoft从CRM 2016(8.x)SDK客户端删除了Microsoft.Xrm.Client,因为它不符合OAuth更改,并将其替换为Microsoft.Xrm.Tooling.Connector。
  3. Microsoft通过删除对ACS的所有引用来修改其SDK身份验证代码。从Microsoft Dynamics CRM Online 2016 Update 1(v8.1.1)和Microsoft Dynamics 365(v8.2)版本开始生效。他们还在服务器端删除了Live ID支持和ACS依赖项。
  4. https://blogs.msdn.microsoft.com/crm/2017/02/01/dynamics-365-sdk-backwards-compatibility/

    建议的方法是使用Microsoft.Xrm.Tooling.Connector。请参阅以下示例:

    https://msdn.microsoft.com/en-us/library/jj602970.aspx

    XML

    Enable

    这是C#代码

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <connectionStrings>
        <!-- Online using Office 365 -->
        <!-- <add name="Server=CRM Online, organization=contoso, user=someone"
             connectionString="Url=https://contoso.crm.dynamics.com; Username=someone@contoso.onmicrosoft.com; Password=password; authtype=Office365"/> -->
    
        <!-- On-premises with provided user credentials -->
        <!-- <add name="Server=myserver, organization=AdventureWorksCycle, user=administrator"
             connectionString="Url=http://myserver/AdventureWorksCycle; Domain=mydomain; Username=administrator; Password=password; authtype=AD"/> -->
    
        <!-- On-premises using Windows integrated security -->
        <!-- <add name="Server=myserver, organization=AdventureWorksCycle"
             connectionString="Url=http://myserver/AdventureWorksCycle; authtype=AD"/> -->
    
        <!-- On-Premises (IFD) with claims -->
        <!--<add name="Server=litware.com, organization=contoso, user=someone@litware.com"
             connectionString="Url=https://contoso.litware.com; Username=someone@litware.com; Password=password; authtype=IFD"/>-->
      </connectionStrings>
      <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
      </startup>
    <system.diagnostics>
        <trace autoflush="true"/>
        <sources>
          <source name="Microsoft.Xrm.Tooling.Connector.CrmServiceClient" switchName="Microsoft.Xrm.Tooling.Connector.CrmServiceClient" switchType="System.Diagnostics.SourceSwitch">
            <listeners>
              <add name="console" type="System.Diagnostics.ConsoleTraceListener"/>
              <add name="fileListener"/>
            </listeners>
          </source>
          <source name="Microsoft.Xrm.Tooling.CrmConnectControl" switchName="Microsoft.Xrm.Tooling.CrmConnectControl" switchType="System.Diagnostics.SourceSwitch">
            <listeners>
              <add name="console" type="System.Diagnostics.ConsoleTraceListener"/>
              <add name="fileListener"/>
            </listeners>
          </source>
          <source name="CrmSvcUtil" switchName="CrmSvcUtil" switchType="System.Diagnostics.SourceSwitch">
            <listeners>
              <add name="console" type="System.Diagnostics.ConsoleTraceListener"/>
              <add name="fileListener"/>
            </listeners>
          </source>
        </sources>
        <switches>
    
          <!--Possible values for switches: Off, Error, Warning, Information, Verbose
                            Verbose:      includes Error, Warning, Info, Trace levels
                            Information:  includes Error, Warning, Info levels
                            Warning:      includes Error, Warning levels
                            Error:        includes Error level-->
    
          <add name="Microsoft.Xrm.Tooling.CrmConnectControl" value="Off"/>
          <add name="Microsoft.Xrm.Tooling.Connector.CrmServiceClient" value="Error"/>
          <add name="CrmSvcUtil" value="Off"/>
        </switches>
    
        <sharedListeners>
          <add name="fileListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="CrmSvcUtil.log"/>
        </sharedListeners>
    
      </system.diagnostics>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="Microsoft.Xrm.Sdk" publicKeyToken="31bf3856ad364e35" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="8.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="Microsoft.Xrm.Sdk.Deployment" publicKeyToken="31bf3856ad364e35" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="8.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="Microsoft.ServiceBus" publicKeyToken="31bf3856ad364e35" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-2.4.0.0" newVersion="2.4.0.0" />
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
    </configuration>