11from __future__ import unicode_literals
22
3+ import json
4+
35from oauthlib import oauth2
46from oauthlib .common import urlencode , urlencoded , quote
57
@@ -33,19 +35,37 @@ def _get_escaped_full_path(self, request):
3335 def _extract_params (self , request ):
3436 """
3537 Extract parameters from the Django request object. Such parameters will then be passed to
36- OAuthLib to build its own Request object
38+ OAuthLib to build its own Request object. The body should be encoded using OAuthLib urlencoded
3739 """
3840 uri = self ._get_escaped_full_path (request )
3941 http_method = request .method
42+ headers = self .extract_headers (request )
43+ body = urlencode (self .extract_body (request ))
44+ return uri , http_method , body , headers
45+
46+ def extract_headers (self , request ):
47+ """
48+ Extracts headers from the Django request object
49+ :param request: The current django.http.HttpRequest object
50+ :return: a dictionary with OAuthLib needed headers
51+ """
4052 headers = request .META .copy ()
4153 if 'wsgi.input' in headers :
4254 del headers ['wsgi.input' ]
4355 if 'wsgi.errors' in headers :
4456 del headers ['wsgi.errors' ]
4557 if 'HTTP_AUTHORIZATION' in headers :
4658 headers ['Authorization' ] = headers ['HTTP_AUTHORIZATION' ]
47- body = urlencode (request .POST .items ())
48- return uri , http_method , body , headers
59+
60+ return headers
61+
62+ def extract_body (self , request ):
63+ """
64+ Extracts the POST body from the Django request object
65+ :param request: The current django.http.HttpRequest object
66+ :return: provided POST parameters
67+ """
68+ return request .POST .items ()
4969
5070 def validate_authorization_request (self , request ):
5171 """
@@ -136,6 +156,24 @@ def verify_request(self, request, scopes):
136156 return valid , r
137157
138158
159+ class JSONOAuthLibCore (OAuthLibCore ):
160+ """
161+ Extends the default OAuthLibCore to parse correctly requests with application/json Content-Type
162+ """
163+ def extract_body (self , request ):
164+ """
165+ Extracts the JSON body from the Django request object
166+ :param request: The current django.http.HttpRequest object
167+ :return: provided POST parameters "urlencodable"
168+ """
169+ try :
170+ body = json .loads (request .body .decode ('utf-8' )).items ()
171+ except ValueError :
172+ body = ""
173+
174+ return body
175+
176+
139177def get_oauthlib_core ():
140178 """
141179 Utility function that take a request and returns an instance of
@@ -144,4 +182,4 @@ def get_oauthlib_core():
144182 from oauthlib .oauth2 import Server
145183
146184 server = Server (oauth2_settings .OAUTH2_VALIDATOR_CLASS ())
147- return OAuthLibCore (server )
185+ return oauth2_settings . OAUTH2_BACKEND_CLASS (server )
0 commit comments