Restructured authentication so the same code can work with callbacks.