Skip to content

Commit

Permalink
Revert oauthlib behaviour
Browse files Browse the repository at this point in the history
Previously, a 401 was returned when invalid credentials were used with the Resource Owner Password Credentials Grant flow.
See oauthlib/oauthlib#264 and oauthlib/oauthlib#619
Versions 3+ return 400 making it tougher to distinguish between incorrect passwords and other errors.
This patch reverts the status code back to 401, but only in the case where credentials were incorrect.
  • Loading branch information
ushkarev committed Nov 10, 2021
1 parent 53bab93 commit 676402b
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
36 changes: 36 additions & 0 deletions mtp_api/apps/mtp_auth/patches.py
@@ -0,0 +1,36 @@
import json

from oauth2_provider.views import TokenView


class ModifiedTokenView(TokenView):
"""
Patches responses to be like those returned by `oauthlib` prior to version 3.
Previously, a 401 was returned when invalid credentials were used with
the Resource Owner Password Credentials Grant flow.
See https://github.com/oauthlib/oauthlib/issues/264 and https://github.com/oauthlib/oauthlib/issues/619
Versions 3+ return 400 making it tougher to distinguish between incorrect passwords and other errors.
This patch reverts the status code back to 401, but only in the case where credentials were incorrect.
"""
# Sample of a true 400 response:
# {"error": "unsupported_grant_type"}
# Sample of a true 403 response (e.g. when request and credentials are valid, but client does not match):
# {"error": "restricted_client"}
# Sample of a response that will be reverted to 401
# {"error": "invalid_grant", "error_description": "Invalid credentials given."}
def post(self, request, *args, **kwargs):
response = super().post(request, *args, **kwargs)
if response.status_code == 400:
response_content = json.loads(response.content)
if (
response_content.get('error') == 'invalid_grant' and
'Invalid credentials given' in response_content.get('error_description')
):
response.status_code = 401
return response


def patch_oauth2_provider_token_view():
import oauth2_provider.views

oauth2_provider.views.TokenView = ModifiedTokenView
3 changes: 3 additions & 0 deletions mtp_api/urls.py
Expand Up @@ -7,8 +7,11 @@
from moj_irat.views import HealthcheckView, PingJsonView
from mtp_common.metrics.views import metrics_view

from mtp_auth.patches import patch_oauth2_provider_token_view
from .views import schema_view

patch_oauth2_provider_token_view()


urlpatterns = [
url(r'^', include('prison.urls')),
Expand Down

0 comments on commit 676402b

Please sign in to comment.