Datasource Authentication via Routes for Grafana Datasource Plugin

I’m trying to write a custom datasource plugin for Grafana that would request Azure AD authentication tokens and send them along with the queries to my database which will accept the token and return the response to the query.

I’ve noticed that the Azure Monitor Plugin for Grafana does the same by asking the user to enter their client id, client secret and tenant id and using it via the routes{} part of their plugin.json file.

I have followed this method but I get a 502 bad gateway error.
My files are hosted here

The essential part of my datasource.js that makes the HTTP call is

query(options) {

    const csl = document.getElementById("csl").value;
    var queries = _.filter(options.targets, item => {
        return item.hide !== true;
      }).map(item => {
        return {
          refId: item.refId,
          intervalMs: options.intervalMs,
          maxDataPoints: options.maxDataPoints,
          format: item.format,
        };
      });
    if (queries.length <= 0) {
      return this.$q.when({data: []});
    }
    return this.backendSrv.datasourceRequest({
        url: `api/datasources/proxy/${this.id}/kusto/query`,
        method: 'POST',
        headers: this.headers,
        data: {
            db: this.database,
            csl: csl,
            from: options.range.from,
            to: options.range.to,
            queries: queries,
        }
    });
}

Where kusto is the routes path defined in my plugin.json.

What is causing this error? Is there a mistake in my datasource.js or my plugin.json? Is the error happening client side or server side?

I can’t speak about your particular problem, and your code looks correct at a glance, but I’ll note what I’ve learned after having gone through this similarly vague issue.

First off, the error is most likely serverside, as that error is thrown if grafana’s http client can’t make the request because of malformed requests.

The first thing you can try is use your plugin on different versions of Grafana. I found that for our plugin.json to work, we needed Grafana version 5.3.x, as that was when they added/fixed interpolation for JsonData to the URL parameter of a Route.

Turning on logging in the .ini file also revealed that the URL wasn’t being interpolated, Logging can reveal similar issues with this plugin.

Also, if you’ve got persistent data storing, the secret_key set in the .ini must match what it was set to when the client secret was first set on the config screen.

Those were my two issues that weren’t immediately obvious to me on the first go.

Answered this on StackOverflow: https://stackoverflow.com/a/53447851/22688

The error is that the code for the testDatasource function is a HTTP GET request and the route only matches for POST requests. Otherwise the code looks correct I think.