Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for the approval_prompt parameter used in the Google OAUTH2 API #65

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,24 @@
To have the provider only create and retrieve one access token per
user/client/scope combination, set to `True`.

.. attribute:: ENABLE_APPROVAL_PROMPT_BYPASS

:settings: `OAUTH_ENABLE_APPROVAL_PROMPT_BYPASS`
:default: `False`

Enable an optional `approval_prompt` parameter in authorization requests.
This parameter is described in
`Googles OAUTH2 API <https://developers.google.com/accounts/docs/OAuth2WebServer#formingtheurl>`_
documentation.

The approval_prompt parameter accepts two values, `force` (default) and `auto`.

The approval prompt is skipped and a grant token is provided immediately if an authorization request
matches an valid access token and `approval_promt` is set to `auto`.

This setting is ideal if the OAUTH2 API is used as an authentication service, and you want to avoid
re-prompting the user for OAUTH2 access each time he authenticates.

`provider.forms`
----------------
.. automodule:: provider.forms
Expand Down
2 changes: 2 additions & 0 deletions provider/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,5 @@
SESSION_KEY = getattr(settings, 'OAUTH_SESSION_KEY', 'oauth')

SINGLE_ACCESS_TOKEN = getattr(settings, 'OAUTH_SINGLE_ACCESS_TOKEN', False)

ENABLE_APPROVAL_PROMPT_BYPASS = getattr(settings, 'OAUTH_ENABLE_APPROVAL_PROMPT_BYPASS', False)
24 changes: 24 additions & 0 deletions provider/oauth2/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,11 @@ class AuthorizationRequestForm(ScopeMixin, OAuthForm):
The scope that the authorization should include.
"""

approval_prompt = forms.CharField(required=False)
"""
Force usage of the approval prompt, or bypass it if a valid access token exists.
"""

def clean_response_type(self):
"""
:rfc:`3.1.1` Lists of values are space delimited.
Expand Down Expand Up @@ -172,6 +177,25 @@ def clean_redirect_uri(self):

return redirect_uri

def clean_approval_prompt(self):
"""
Accepts "force" and "auto". Defaults to "force" for backwards compatibility.
"""

approval_prompt = self.cleaned_data.get('approval_prompt')

if not approval_prompt:
approval_prompt = 'force'

if approval_prompt not in ["force", "auto"]:
raise OAuthValidationError({
'error': 'unsupported_approval_prompt',
'error_description':
u"'%s' is not a supported approval prompt " % approval_prompt
})

return approval_prompt


class AuthorizationForm(ScopeMixin, OAuthForm):
"""
Expand Down
138 changes: 110 additions & 28 deletions provider/oauth2/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from django.http import QueryDict
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test.utils import override_settings
from django.utils.html import escape
from django.test import TestCase
from django.contrib.auth.models import User
Expand Down Expand Up @@ -46,17 +47,46 @@ def get_user(self):
def get_password(self):
return 'test'

def _login_and_authorize(self, url_func=None):
def _login_and_authorize(self, url_func=None, request_scope=None):
if url_func is None:
url_func = lambda: self.auth_url() + '?client_id=%s&response_type=code&state=abc' % self.get_client().client_id

if request_scope is None:
request_scope = constants.SCOPES[0][1]

response = self.client.get(url_func())
response = self.client.get(self.auth_url2())

response = self.client.post(self.auth_url2(), {'authorize': True, 'scope': constants.SCOPES[0][1]})
response = self.client.post(self.auth_url2(), {'authorize': True, 'scope': request_scope})
self.assertEqual(302, response.status_code, response.content)
self.assertTrue(self.redirect_url() in response['Location'])

def _login_authorize_get_token(self, request_scope=None):
required_props = ['access_token', 'token_type']

self.login()
self._login_and_authorize(request_scope=request_scope)

response = self.client.get(self.redirect_url())
query = QueryDict(urlparse.urlparse(response['Location']).query)
code = query['code']

response = self.client.post(self.access_token_url(), {
'grant_type': 'authorization_code',
'client_id': self.get_client().client_id,
'client_secret': self.get_client().client_secret,
'code': code})

self.assertEqual(200, response.status_code, response.content)

token = json.loads(response.content)

for prop in required_props:
self.assertIn(prop, token, "Access token response missing "
"required property: %s" % prop)

return token


class AuthorizationTest(BaseOAuth2TestCase):
fixtures = ['test_oauth2']
Expand Down Expand Up @@ -238,32 +268,6 @@ def test_fetching_access_token_with_invalid_grant(self):
self.assertEqual(400, response.status_code, response.content)
self.assertEqual('invalid_grant', json.loads(response.content)['error'])

def _login_authorize_get_token(self):
required_props = ['access_token', 'token_type']

self.login()
self._login_and_authorize()

response = self.client.get(self.redirect_url())
query = QueryDict(urlparse.urlparse(response['Location']).query)
code = query['code']

response = self.client.post(self.access_token_url(), {
'grant_type': 'authorization_code',
'client_id': self.get_client().client_id,
'client_secret': self.get_client().client_secret,
'code': code})

self.assertEqual(200, response.status_code, response.content)

token = json.loads(response.content)

for prop in required_props:
self.assertIn(prop, token, "Access token response missing "
"required property: %s" % prop)

return token

def test_fetching_access_token_with_valid_grant(self):
self._login_authorize_get_token()

Expand Down Expand Up @@ -432,6 +436,84 @@ def test_access_token_response_valid_token_type(self):
self.assertEqual(token['token_type'], constants.TOKEN_TYPE, token)


class ApprovalPromptTest(BaseOAuth2TestCase):
fixtures = ['test_oauth2']

def setUp(self):
constants.ENABLE_APPROVAL_PROMPT_BYPASS = True

def tearDown(self):
constants.ENABLE_APPROVAL_PROMPT_BYPASS = False

def test_get_second_token_without_prompt(self):

self._login_authorize_get_token()

# Now we should be able to get an access token skipping the approval promt
# Notice approval_prompt in the url

url = self.auth_url() + '?client_id=%s&response_type=code&state=abc&approval_prompt=auto' \
% self.get_client().client_id

response = self.client.get(url)
response = self.client.get(self.auth_url2())

# Notice! we get the redirect immediately

self.assertEqual(302, response.status_code, response.content)
self.assertTrue(self.redirect_url() in response['Location'])

def test_use_force_by_default(self):

self._login_authorize_get_token()

url = self.auth_url() + '?client_id=%s&response_type=code&state=abc' % self.get_client().client_id

response = self.client.get(url)
response = self.client.get(self.auth_url2())

self.assertEqual(200, response.status_code, response.content)

def test_always_prompt_if_no_access_token(self):

AccessToken.objects.all().delete()

self.login()

url = self.auth_url() + '?client_id=%s&response_type=code&state=abc&approval_prompt=auto' \
% self.get_client().client_id

response = self.client.get(url)
response = self.client.get(self.auth_url2())

self.assertEqual(200, response.status_code, response.content)

def test_skip_prompt_if_scope_is_less(self):

self._login_authorize_get_token(request_scope='write')

url = self.auth_url() + '?client_id=%s&response_type=code&state=abc&scope=read&approval_prompt=auto' \
% self.get_client().client_id

response = self.client.get(url)
response = self.client.get(self.auth_url2())

self.assertEqual(302, response.status_code, response.content)
self.assertTrue(self.redirect_url() in response['Location'])

def test_prompt_if_scope_is_greater(self):

self._login_authorize_get_token()

url = self.auth_url() + '?client_id=%s&response_type=code&state=abc&scope=write&approval_prompt=auto' \
% self.get_client().client_id

response = self.client.get(url)
response = self.client.get(self.auth_url2())

self.assertEqual(200, response.status_code, response.content)


class AuthBackendTest(BaseOAuth2TestCase):
fixtures = ['test_oauth2']

Expand Down
25 changes: 24 additions & 1 deletion provider/oauth2/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from .forms import AuthorizationRequestForm, AuthorizationForm
from .forms import PasswordGrantForm, RefreshTokenGrantForm
from .forms import AuthorizationCodeGrantForm
from .models import Client, RefreshToken, AccessToken
from .models import Client, RefreshToken, AccessToken, Grant
from .backends import BasicClientBackend, RequestParamsClientBackend, PublicPasswordBackend


Expand Down Expand Up @@ -38,6 +38,29 @@ def get_client(self, client_id):
def get_redirect_url(self, request):
return reverse('oauth2:redirect')

def reuse_authorization(self, request, client, client_data):

has_access_token = AccessToken.objects.filter(
user=request.user,
client=client,
scope__gte=client_data.get('scope'),
expires__gt=now()
).exists()

if has_access_token:

grant = Grant.objects.create(
user=request.user,
client=client,
scope=client_data.get('scope'),
redirect_uri=client_data.get('redirect_uri', '')
)

return grant.code

else:
return None

def save_authorization(self, request, client, form, client_data):

grant = form.save(commit=False)
Expand Down
36 changes: 27 additions & 9 deletions provider/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,17 @@ def get_client(self, client_id):
"""
raise NotImplementedError

def reuse_authorization(self, request, client, client_data):
"""
Return existing authorization code grant if the request matches a
previously granted (and still active) access token.

Used to implement the approval_prompt parameter used in Google's OAUTH2.

:return: ``None``, ``str``
"""
raise NotImplementedError

def save_authorization(self, request, client, form, client_data):
"""
Save the authorization that the user granted to the client, involving
Expand Down Expand Up @@ -258,17 +269,24 @@ def handle(self, request, post_data=None):
except OAuthError, e:
return self.error_response(request, e.args[0], status=400)

authorization_form = self.get_authorization_form(request, client,
post_data, data)
code = None

if constants.ENABLE_APPROVAL_PROMPT_BYPASS and \
data.get('approval_prompt', 'force') == 'auto':
code = self.reuse_authorization(request, client, data)

if code is None:
authorization_form = self.get_authorization_form(request, client,
post_data, data)

if not authorization_form.is_bound or not authorization_form.is_valid():
return self.render_to_response({
'client': client,
'form': authorization_form,
'oauth_data': data, })
if not authorization_form.is_bound or not authorization_form.is_valid():
return self.render_to_response({
'client': client,
'form': authorization_form,
'oauth_data': data, })

code = self.save_authorization(request, client,
authorization_form, data)
code = self.save_authorization(request, client,
authorization_form, data)

# be sure to serialize any objects that aren't natively json
# serializable because these values are stored as session data
Expand Down