Pages

2019-03-26

Using HTTP Basic Auth (with Logout!) in a Go Application

HTTP Basic Auth (Wikipedia) is a thing that is actually still quite useful despite its neglect in modern web standards. By neglect, I mean that it hasn't been updated since its introduction in RFC7617 and as such the logout mechanism hasn't been improved to take into account modern browsers' tendency to aggressively cache session data within the HTTP headers, which is where the login state is stored. However, with some tricks it still can reliably be used in modern browsers. But some Javascript is required, sorry :(

First, a note: don't even consider using HTTP basic auth in your public-facing page unless you have it served behind an HTTPS reverse proxy! The username and password sent to and fro from client to server is in plaintext by default, and only HTTPS with TLS will guarantee that the entire request including the critical HTTP headers are encrypted.

Given that caveat, here is a complete minimal example of using HTTP basic auth to gate access to a Go http app.

Go Playground Example <-- this won't work in the Playground -- copy and build locally

FAQ

Q: Go's http lib supports TLS to serve out endpoints. Why didn't you just do that instead of serving out an HTTP app behind a reverse proxy?
A: HTTP basic auth seems to be mutually exclusive with the HTTPS protocol. Perhaps I missed something. Let me know if I'm wrong, and how to do it. Thanks.

Q: How do I support multiple users/roles using the example you give?
A: No idea. I think it could be done, with auxiliary logic to track separate session users/passwords, but this is left as an exercise for the reader. [Meaning, like all my college profs ... I forget/I can't be arsed to work it out right now.]

-R.

No comments:

Post a Comment