Change check_authentication function for more flexible

Hi Jeffrey,

I need a way to return custom response to client when authentication is failed.
Please, see my commits.