Tuesday, November 24, 2015

Quick Take On MS CRM Dynamics, java, scala and AD Authentication

I needed to connect to MS CRM Dynamics using a simple java. The main instructions are on MSDN.
First, I had to register my application in the Azure AD using a "native" client app and ensure that it was given permission to access my MS CRM instance.
Then I followed the instructions. I found a few blogs including one that seems to hit on my wanting to test my connection. Jason Lattimer had already done the hard work. But I found that I just wanted to test this out quickly without creating a java program.
So I fired up scala's amm. amm is a new scala repl. It allows you to do things on the fly. I also looked at the example code from the java library that microsoft created.
load.ivy("com.microsoft.azure" % "adal4j" % "latest.release")
val authority = "https://login.windows.net/common"
val clientid = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
import java.util.concurrent._
val eservice = Executors.newFixedThreadPool(1)
val resource="https://yourdomain.crm.dynamics.com"
val resultFuture = context.acquireToken(resource, clientid, "username@yourdomain.onmicrosoft.com", "password", null)
resultFuture.get
which results in:
res15: AuthenticationResult = com.microsoft.aad.adal4j.AuthenticationResult@40d8ea60
Unfortunately, this is not very scala, and java futures are not great but this does illustrate that everything worked as planned.
amm has a robust tab completer so you can hit tab on the result:
val t = resultFuture.get
t.<hit tab>
!=                                  getAccessToken                      getExpiresOnDate                    hashCode                            |>
==                                  getAccessTokenType                  getIdToken                          isInstanceOf
asInstanceOf                        getClass                            getRefreshToken                     isMultipleResourceRefreshToken
equals                              getExpiresAfter                     getUserInfo                         toString
and navigate through the result.
Jason worked up a nice, more complete example of using the new web api here.
You will note that the adal4j library has many assumptions and dependencies that it pulls in and assumes an execution model underneath. Yo ucould of course program your own using something more pluggable, but unfortunately, that's alot of work if you just need to connect quickly. Underneath it uses:
  • nimbus oauth2
  • bouncycastle (java crypto api)
  • ...a few others...
Underneath, adal4j uses javax.net standard java classes for transport. The nimbus classes are used to construct an OAuth2 request and process the return headers, etc.
If you get a strange error, e.g. something about the request body needing some specific content, you may have created a web app OAuth2 application grant instead of a "client" application. See here for details.

No comments:

Post a Comment