V6 API 401Unauthorized Issues

When the cookie is used to send the SID, you'll also need to send the CSRF token provided by the API during login. This is to prevent possible Cross-Site-Request-Forgery attacks and commonly found with web APIs. If you'd rely on authentication via cookie only, third-party pages could send requests to your Pi-hole (and the browser would automatically attach the cookie to this request) when you happen to be logged in in the same browser (which is quite likely). Hence, a second secret (the CSRF token) needs to be added that is not available to third party sites.
If you open the Pi-hole web interface and use the Developer tools, you will see that this is precisely what the Pi-hole web interface does when communication with the API.

Example from a Pi-hole web interface request:


When you go to index - powered by h5ai v0.30.0 (https://larsjung.de/h5ai/) and hover over the available authentication methods for endpoint on the top right of each individual endpoint, you will notice that using the Authorization header isn't the right choice (following its documentation, the Authorization header is used only for Basic and Digest authentication, both aren't used by Pi-hole).

You can either use

  • sid in any JSON payload you are sending to the API (if the endpoint accepts a payload), or
  • sid provided by a cookie + CSRF token in header X-CSRF-TOKEN (see Pi-hole web interface), or
  • sid in the header, or
  • X-FTL-SID in the header

We will shortly be working on documenting this more explicitly. I am sorry we haven't done this before but we probably have, for once, forgotten about it with all the changes we did to the new API and, secondly, we also didn't expect early-adopters before the official announcement of v6.0 beta.

1 Like