Token authentication logic and tests