Ontoserver and FHIR authentication with C#

By | April 21, 2018

Last week during the NCTS Connectathon, I was connecting to the CSIRO’s public Ontoserver. Afterwards, I tried connecting to the NTS and remembered that it requires authentication. The NCTS documentation along with accompanying postman collection is helpful, so let’s see how we can do it in C#. The authentication endpoint for NTS is not the same as the FHIR endpoint. So you’ll need to connect with RestSharp (or similar).


System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
var authClient = new RestClient("https://api.healthterminologies.gov.au/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddQueryParameter("grant_type", "client_credentials");

// Request Token, via request body
request.AddQueryParameter("client_id", "35e...f73");
request.AddQueryParameter("client_secret", "cbf...d9b");

IRestResponse response = authClient.Execute(request);
var resp = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Content);

access_token = resp["access_token"]

Note: it’s important to set the security protocol. Otherwise, the server will not accept requests.

Also, I like sending the request token client Id and secret as query parameters, but you can also use a Basic Authentication header:


//Request Token, via Basic Auth header
var authtoken = Convert.ToBase64String(Encoding.UTF8.GetBytes("35e...f73:cbf...d9b"));
request.AddHeader("authorization", "Basic " + authtoken);

So getting the Authorisation Token is probably easy enough if you’ve worked with Oauth before, but how do we authenticate our FHIR API calls? There’s some advice on Github, here and here. You need to add authorisation to the header for each call. The value for the Bearer token, being the access_token acquired above.


fhirClient.OnBeforeRequest += (object sender, BeforeRequestEventArgs e) =>
{
e.RawRequest.Headers.Add("Authorization", @"Bearer eyJ0e-...-xkcd");
};

The authentication response also gives you refresh token, I’m not sure what to do with that but don’t appear to be alone. Either way, you’ll have to monitor the expiry of the access_token and renew as required.

Leave a Reply

Your email address will not be published. Required fields are marked *