Forward logged-in username to datasource?

I’m using auth.proxy and want to forward the username of the logged-in user to my custom data source. How is this possible? There are the options “With credentials” and “Forward OAuth Identity”, but the former doesn’t seem to do anything, and while the latter sounds like the thing I need, it only seems to work with OAuth. But how can I simply pass the username along? Custom headers also do not help, as there doesn’t seem to be a way to pass the username as a variable or so, only static values.
Is this currently not implemented? How could I work around this?
Thank you very much in advance!

Hi @mstud, that’s a good question that I’m also trying to figure out. AFAIK it’s not supported out of the box. I have two ideas in mind as to how it might be implemented. To be clear, I’ve not implemented either end-to-end; they’re just proposals. The datasource in mind here is Influx, proxied through a layer that can do something useful with the user ID that’s passed to it. This may vary somewhat for others.

What I suggest is either one of:

Option 1: The simple code change
In the code that handles datasource proxy requests (https://github.com/grafana/grafana/blob/master/pkg/api/pluginproxy/ds_proxy.go), in the getDirector() function add a line like

req.Header.Add("X-Grafana-Username", proxy.ctx.Login)

This then obviously only works for datasource queries that are being proxied through the Grafana server.

Option 2: The workaround
If you have a reasonably high level of flexibility in terms of your datasource endpoint, you could do the following:

  1. Ensure that your datasource can access the grafana_session cookie set in the user’s browser. To achieve this, either add “grafana_session” under Whitelisted Cookied in the datasource config, or run the datasource connection in Browser mode, and put the datasource endpoint on the same domain/host.
  2. In your datasource itself, take the grafana_session cookie that’s been passed to it, and use it to do a GET request to the https://[grafana-domain]/api/user endpoint of Grafana’s API. That will return the logged in user info. You’ll probably want to cache the obtained session => user info association, to avoid hammering the API with identical requests for every query a user executes.

Note that especially for Option 1, you’ll need to take additional measures to prevent spoofing of the provided user ID.

Would appreciate any input on the viability/validity of the above.

When looking over the code again, I realized I was wrong about it not being implemented out of the box. It’s actually a global configuration option: https://grafana.com/docs/grafana/latest/administration/configuration/#send_user_header
(defaults to false)

1 Like

Thank you very much, that was exactly what I was looking for!

Indeed - this is great for our use case also! It’s weird because I’m sure I’ve looked for this before and not found it.