Added extra check whether authorization is needed.
Added unit tests and better exception messages.