cherry pick 863a62adaeba56a5f8f74aa0e8f2f9c98f9ba0c2 and small adaptation from git://github.com/songkick/oauth2-provider.git