Monday, February 9, 2015

SOAP Only Authentication Using C#

In most cases when writing code to connect to Dynamics CRM you'll hit up the SDK assemblies so you can establish your connection and get down to business in just a few lines of code. Inevitably there will be situations where using the those assemblies might not be an option, case in point non-.NET languages.

Obviously authentication is the first major problem that needs to be solved before you can get into the meat of your application. If you browse through the CRM SDK under the "Write mobile and modern apps" topic you'll notice that using OAuth is the recommended approach to authentication. Which is fine but in order to do so you'll need to register your application ahead of time with Active Directory (Online or On Premise) which isn't always desirable or possible.

An alternative approach is to communicate with CRM using raw SOAP requests. Using this approach we can authenticate to CRM Online or On Premise IFD organizations with a user's same credentials and return back the correct security tokens that need to accompany any future requests. Obviously working directly with the SOAP XML isn't that pretty but it can be done. This should provide a starting point for converting to other languages. I'll be posting examples in the near future for PHP, Java, JavaScript (mobile application), and VBA.

I've put together a couple of sample applications, the first is a C# console application that can authenticate to CRM using SOAP requests and then returns back the name of the logged in user.

The second is a mobile application using the Xamarin platform. If you aren't familiar with Xamarin it allows you to develop native iOS, Android, and Windows mobile applications using C# and Visual Studio. Unfortunately for us CRM developers the SDK assemblies have dependencies on other .NET assemblies that are not supported by Xamarin which makes the standard versions of the CRM SDK assemblies not viable (mobile versions here + other mobile samples). Full disclosure: Xamarin supports the developer community by giving Microsoft MVPs complimentary licenses - which I appreciate greatly!

The second sample does the same thing except it is in the form of a Xamarin iOS (requires Xamarin to run) application.


The heavy lifting for generating the SOAP headers looks like this: