Was looking at trying to find an example of leveraging the fhir-net-api to create a FHIR client server side and pass in an authorization token that is being passed back from a smart on fhir client application to my web server to make calls to the FHIR server where the token was generated/valid and not finding any examples of adding a token to the FHIR client before making the call to the FHIR server in the .net fhir documentation as the examples are all hitting public endpoints.
Do I just add it as a search parameter or is there something I am missing that I need to do to leverage the token when calling a non-public API that requires the token? I noticed that there is a token type in the search parameters but not sure how to leverage it... Here is a basic example of making a generic search call to an observation endpoint where I think I need to add the token as a search parameter:
_fhirClient = new FhirClient(openApi);
_fhirClient.PreferredFormat = ResourceFormat.Json;
_fhirSearchParamaters = new SearchParams();
_fhirSearchParamaters.Add("patient", mrn);
//Not sure where to add this token to the FHIR client
//before executing the search call to get the bundle from the FHIR server...
_fhirSearchParamaters.Add("token", token);
_fhirSearchParamaters.Add("code", "58941-6");
//return the bundle from the FHIR server
return _fhirClient.Search(_fhirSearchParamaters);
You can add a header to the call in the OnBeforeRequest event of the client like this:
_fhirClient.OnBeforeRequest += (object sender, BeforeRequestEventArgs e) =>
{
// Replace with a valid bearer token for the server
e.RawRequest.Headers.Add("Authorization", "Bearer XXXXXXX");
};
The documentation for this can be found here: http://docs.simplifier.net/fhirnetapi/client/request-response.html#fhirclient-event-handlers.
Looks like the new way to do it with 2.0 version:
var messageHandler = new HttpClientEventHandler();
string token = {{get your token}};
messageHandler.OnBeforeRequest += (object sender, BeforeHttpRequestEventArgs e) =>
{
e.RawRequest.Headers
.Add("Authorization", $"Bearer {token}");
////var request = Encoding.UTF8.GetString(e.Body, 0, e.Body.Length);
};
Hl7.Fhir.Rest.FhirClient client = new Hl7.Fhir.Rest.FhirClient(endpoint, messageHandler: messageHandler, settings: new FhirClientSettings()
{
PreferredFormat = ResourceFormat.Json
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With