Refactor authentication
Fix #372 (closed).
This refactoring improves the reliability of the authentication process. It fixes a number of bugs (e.g. logout that doesn't log out of SSO) and provides some welcome improvements (e.g. session auto-refresh on expiry).
I've ordered the comments to ease the review.