Search code examples
rauthenticationdynamics-crmadfshttr

Trying to authenticate to MS Dynamics CRM 2016 WebApi using R


I could use some help..

I am trying to connect to a MS Dynamics CRM (2016) on-premise database. it is facing the internet (IFD) and uses adfs 3.0 to authenticate users.

Now, when I try to connect to the api using the webbrouwser, a smal log-in form appears that lets me enter my username and password. When I submit these credentials, the browser opens a page with nice json code, however, when I try the following code in R

library(httr)

result <- GET(
   "https://xrm.company.nl/Company/api/data/v8.2/some=query",
   config = authenticate(
      user = "MyUsername",
      password = "MyPassword",
      type = "ntlm"
   )
)

I get text/html content that builds a POST form. This form is already filled out for me, but it relies on some js script to auto submit. There's also is a warning message available in the html that says that script is disabled combined with a handy (but unreachable) submit button.

When I extract the html from the content content(result, as = "text"), put it in an html file and open it in my browser, the json results sow up.

But I don't know how to enable script, or how to click submit using R.

Anybody any ideas for a workaround for these issues, or on how to authenticate correctly to adfs using R?


Solution

  • You will to request a SAML bearer access token. See this post on the Magnatism blog: Dynamics 365 Online ADFS Authenticate with User Credentials

    In a nut shell you need to do the following...

    1. Get User Realm by Sending HTTP GET Request to User Realm Endpoint
    2. Get SAML Access Token by Sending HTTP POST Request to ADFS Service Endpoint
    3. Extract XML content Between the Element, Remove Any Indenting then Encode to Base 64 String
    4. Get SAML Bearer Access Token by Sending HTTP POST Request to Token Endpoint
    5. Set the Authorization Header of the HTTP Request