fix authentication through Rest API, refactored and with test

refactored patch which keeps closer to the original, now also with unittest.