API v1.4

Tutorial 5 of 6

Act for a clinician

Work in NeuroTrax as one of your clinicians, through the API or by opening NeuroTrax for them, signed in.

Your integration can act for the clinician using your EMR, with no password: call the API as them, or give them a button that opens NeuroTrax signed in, or goes straight into an order's test. Both work with the key you set up, and both need scopes granted on request: on_behalf, and sessions.sso for opening NeuroTrax.

The examples reuse the signed helper and TOKEN_URL from Your first call.

1Get a token as the clinician

With the on_behalf scope, your integration can get a token that acts as one of your clinicians: what it creates is theirs, and an order records them as the orderer. Sign a pass with sub set to the clinician's NeuroTrax username or email, and post it as grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer. The pass is your only credential here.

The token lasts 15 minutes and can do no more than the clinician could in the portal. Sign a new pass when you need another.

curl -X POST 'https://api.neurotrax.com/oauth/token' \
  -d grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer \
  -d "assertion=$ASSERTION"
response = requests.post(TOKEN_URL, data={
    "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
    "assertion": signed({"iss": CLIENT_ID, "sub": "dr.jones@riverside.example", "aud": TOKEN_URL}),
})
response.raise_for_status()
clinician_token = response.json()["access_token"]
const delegated = await fetch(TOKEN_URL, {
  method: "POST",
  body: new URLSearchParams({
    grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
    assertion: await signed({ iss: CLIENT_ID, sub: "dr.jones@riverside.example", aud: TOKEN_URL }),
  }),
});
if (!delegated.ok) throw new Error(`${delegated.status} ${await delegated.text()}`);
const clinicianToken = (await delegated.json()).access_token;
var delegated = await http.PostAsync(TokenUrl, new FormUrlEncodedContent(new Dictionary<string, string>
{
    ["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer",
    ["assertion"] = Signed("dr.jones@riverside.example", TokenUrl),
}));
delegated.EnsureSuccessStatusCode();
var clinicianToken = (await delegated.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("access_token").GetString();
var delegation = HttpRequest.newBuilder(URI.create(tokenUrl))
    .header("Content-Type", "application/x-www-form-urlencoded")
    .POST(HttpRequest.BodyPublishers.ofString(
        "grant_type=" + URLEncoder.encode("urn:ietf:params:oauth:grant-type:jwt-bearer", StandardCharsets.UTF_8)
        + "&assertion=" + signed("dr.jones@riverside.example", tokenUrl, java.util.Map.of())))
    .build();
System.out.println(client.send(delegation, HttpResponse.BodyHandlers.ofString()).body()); // access_token
// With signed() from "Your first call"
res, err := http.PostForm(tokenURL, url.Values{
	"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"},
	"assertion":  {signed(jwt.MapClaims{"iss": clientID, "sub": "dr.jones@riverside.example", "aud": tokenURL})},
})
if err != nil {
	panic(err)
}
defer res.Body.Close()
var clinician struct {
	AccessToken string `json:"access_token"`
}
json.NewDecoder(res.Body).Decode(&clinician)
# With signed() from "Your first call"
response = Net::HTTP.post_form(URI(TOKEN_URL),
  "grant_type" => "urn:ietf:params:oauth:grant-type:jwt-bearer",
  "assertion" => signed(iss: CLIENT_ID, sub: "dr.jones@riverside.example", aud: TOKEN_URL))
response.value
clinician_token = JSON.parse(response.body)["access_token"]
// With signed() from "Your first call"
let assertion = signed(json!({ "iss": client_id, "sub": "dr.jones@riverside.example", "aud": TOKEN_URL }))?;
let delegated: Value = client
    .post(TOKEN_URL)
    .form(&[("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"), ("assertion", assertion.as_str())])
    .send()?
    .error_for_status()?
    .json()?;
let clinician_token = delegated["access_token"].as_str().unwrap_or_default().to_string();

2Sign a launch

Build a pass for this one click:

  • iss: your client ID; aud: https://portal.neurotrax.com/reg/sso
  • sub: the clinician's NeuroTrax username or email
  • account: the number of the account to open, one your integration is granted
  • return_to, optional: where to land; leave it out for the front desk
  • exp a minute ahead (at most five), and a fresh jti

Sign it with the same helper.

SSO_URL = "https://portal.neurotrax.com/reg/sso"

def launch_url(clinician, account, return_to=None):
    claims = {"iss": CLIENT_ID, "sub": clinician, "aud": SSO_URL, "account": account}
    if return_to:
        claims["return_to"] = return_to
    return f"{SSO_URL}?launch={signed(claims)}"
const SSO_URL = "https://portal.neurotrax.com/reg/sso";

async function launchUrl(clinician, account, returnTo) {
  const claims = { iss: CLIENT_ID, sub: clinician, aud: SSO_URL, account };
  if (returnTo) claims.return_to = returnTo;
  return `${SSO_URL}?launch=${await signed(claims)}`;
}
const string SsoUrl = "https://portal.neurotrax.com/reg/sso";

string LaunchUrl(string clinician, string account, string? returnTo = null)
{
    var extra = new Dictionary<string, object> { ["account"] = account };
    if (returnTo is not null) extra["return_to"] = returnTo;
    return $"{SsoUrl}?launch={Signed(clinician, SsoUrl, extra)}";
}
String launchUrl(String clinician, String account, String returnTo) throws Exception {
    var ssoUrl = "https://portal.neurotrax.com/reg/sso";
    var extra = new java.util.HashMap<String, Object>(java.util.Map.of("account", account));
    if (returnTo != null) extra.put("return_to", returnTo);
    return ssoUrl + "?launch=" + signed(clinician, ssoUrl, extra);
}
const ssoURL = "https://portal.neurotrax.com/reg/sso"

func launchURL(clinician, account, returnTo string) string {
	claims := jwt.MapClaims{"iss": clientID, "sub": clinician, "aud": ssoURL, "account": account}
	if returnTo != "" {
		claims["return_to"] = returnTo
	}
	return ssoURL + "?launch=" + signed(claims)
}
SSO_URL = "https://portal.neurotrax.com/reg/sso"

def launch_url(clinician, account, return_to = nil)
  claims = { iss: CLIENT_ID, sub: clinician, aud: SSO_URL, account: account }
  claims[:return_to] = return_to if return_to
  "#{SSO_URL}?launch=#{signed(claims)}"
end
const SSO_URL: &str = "https://portal.neurotrax.com/reg/sso";

fn launch_url(client_id: &str, clinician: &str, account: &str, return_to: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
    let mut claims = json!({ "iss": client_id, "sub": clinician, "aud": SSO_URL, "account": account });
    if let Some(path) = return_to {
        claims["return_to"] = json!(path);
    }
    Ok(format!("{SSO_URL}?launch={}", signed(claims)?))
}

3Send the browser there

When the clinician clicks your button, sign a launch and redirect their browser to it straight away. Sign it on click, not ahead of time: each launch works once and expires within minutes. The button itself can be clicked any number of times, to start, to resume, or just to look.

The clinician lands signed in, in that account. Any NeuroTrax session already open in that browser ends.

# Flask
from flask import redirect

@app.post("/neurotrax/open")
def open_neurotrax():
    return redirect(launch_url(current_user.email, current_clinic.neurotrax_account))
// Express
app.post("/neurotrax/open", async (req, res) => {
  res.redirect(await launchUrl(req.user.email, req.clinic.neurotraxAccount));
});
// ASP.NET Core minimal API
app.MapPost("/neurotrax/open", (HttpContext context) =>
    Results.Redirect(LaunchUrl(context.User.Identity!.Name!, "200001")));
// Spring
@PostMapping("/neurotrax/open")
ResponseEntity<Void> openNeuroTrax(Principal user) throws Exception {
    return ResponseEntity.status(HttpStatus.FOUND)
        .location(URI.create(launchUrl(user.getName(), "200001", null)))
        .build();
}
// net/http
http.HandleFunc("POST /neurotrax/open", func(w http.ResponseWriter, r *http.Request) {
	http.Redirect(w, r, launchURL(currentUserEmail(r), "200001", ""), http.StatusFound)
})
# Rails
def open_neurotrax
  redirect_to launch_url(current_user.email, current_clinic.neurotrax_account), allow_other_host: true
end
// axum
async fn open_neurotrax(user: CurrentUser) -> axum::response::Redirect {
    axum::response::Redirect::to(&launch_url(CLIENT_ID, &user.email, "200001", None).unwrap())
}

4Open an order's test

To open an in-clinic test directly, pass the order's launch_path as return_to. The clinician arrives at the test, ready to hand to the patient. A finished, cancelled or ungranted order shows its reason on screen instead.

url = launch_url("dr.jones@riverside.example", "200001", return_to=order["launch_path"])
const url = await launchUrl("dr.jones@riverside.example", "200001", order.launch_path);
var url = LaunchUrl("dr.jones@riverside.example", "200001", order.GetProperty("launch_path").GetString());
var url = launchUrl("dr.jones@riverside.example", "200001", order.get("launch_path").asText());
link := launchURL("dr.jones@riverside.example", "200001", order.LaunchPath)
url = launch_url("dr.jones@riverside.example", "200001", order["launch_path"])
let url = launch_url(&client_id, "dr.jones@riverside.example", "200001", order["launch_path"].as_str())?;