Support authenticated connections (issue #1)

Also, make the code more straightforward