Skip to content
This repository was archived by the owner on Mar 6, 2026. It is now read-only.

Commit 10ec7e9

Browse files
author
Jon Wayne Parrott
authored
Add oauth2 credentials (#24)
1 parent 0a0be14 commit 10ec7e9

File tree

3 files changed

+180
-0
lines changed

3 files changed

+180
-0
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
google.oauth2.credentials module
2+
================================
3+
4+
.. automodule:: google.oauth2.credentials
5+
:members:
6+
:inherited-members:
7+
:show-inheritance:

google/oauth2/credentials.py

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
# Copyright 2016 Google Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""OAuth 2.0 Credentials.
16+
17+
This module provides credentials based on OAuth 2.0 access and refresh tokens.
18+
These credentials usually access resources on behalf of a user (resource
19+
owner).
20+
21+
Specifically, this is intended to use access tokens acquired using the
22+
`Authorization Code grant`_ and can refresh those tokens using a
23+
optional `refresh token`_.
24+
25+
Obtaining the initial access and refresh token is outside of the scope of this
26+
module. Consult `rfc6749 section 4.1`_ for complete details on the
27+
Authorization Code grant flow.
28+
29+
.. _Authorization Code grant: https://tools.ietf.org/html/rfc6749#section-1.3.1
30+
.. _refresh token: https://tools.ietf.org/html/rfc6749#section-6
31+
.. _rfc6749 section 4.1: https://tools.ietf.org/html/rfc6749#section-4.1
32+
"""
33+
34+
from google.auth import _helpers
35+
from google.auth import credentials
36+
from google.oauth2 import _client
37+
38+
39+
class Credentials(credentials.Scoped, credentials.Credentials):
40+
"""Credentials using OAuth 2.0 access and refresh tokens."""
41+
42+
def __init__(self, token, refresh_token=None, token_uri=None,
43+
client_id=None, client_secret=None, scopes=None):
44+
"""
45+
Args:
46+
token (Optional(str)): The OAuth 2.0 access token. Can be None
47+
if refresh information is provided.
48+
refresh_token (str): The OAuth 2.0 refresh token. If specified,
49+
credentials can be refreshed.
50+
token_uri (str): The OAuth 2.0 authorization server's token
51+
endpoint URI. Must be specified for refresh, can be left as
52+
None if the token can not be refreshed.
53+
client_id (str): The OAuth 2.0 client ID. Must be specified for
54+
refresh, can be left as None if the token can not be refreshed.
55+
client_secret(str): The OAuth 2.0 client secret. Must be specified
56+
for refresh, can be left as None if the token can not be
57+
refreshed.
58+
scopes (Sequence[str]): The scopes that were originally used
59+
to obtain authorization. This is a purely informative parameter
60+
that can be used by :meth:`has_scopes`. OAuth 2.0 credentials
61+
can not request additional scopes after authorization.
62+
"""
63+
super(Credentials, self).__init__()
64+
self.token = token
65+
self._refresh_token = refresh_token
66+
self._scopes = scopes
67+
self._token_uri = token_uri
68+
self._client_id = client_id
69+
self._client_secret = client_secret
70+
71+
@property
72+
def requires_scopes(self):
73+
"""False: OAuth 2.0 credentials have their scopes set when
74+
the initial token is requested and can not be changed."""
75+
return False
76+
77+
def with_scopes(self, scopes):
78+
"""Unavailable, OAuth 2.0 credentials can not be re-scoped.
79+
80+
OAuth 2.0 credentials have their scopes set when the initial token is
81+
requested and can not be changed.
82+
"""
83+
raise NotImplementedError(
84+
'OAuth 2.0 Credentials can not modify their scopes.')
85+
86+
@_helpers.copy_docstring(credentials.Credentials)
87+
def refresh(self, request):
88+
access_token, refresh_token, expiry, _ = _client.refresh_grant(
89+
request, self._token_uri, self._refresh_token, self._client_id,
90+
self._client_secret)
91+
92+
self.token = access_token
93+
self.expiry = expiry
94+
self._refresh_token = refresh_token

tests/oauth2/test_credentials.py

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# Copyright 2016 Google Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import datetime
16+
17+
import mock
18+
import pytest
19+
20+
from google.auth import _helpers
21+
from google.oauth2 import credentials
22+
23+
24+
class TestCredentials(object):
25+
TOKEN_URI = 'https://example.com/oauth2/token'
26+
REFRESH_TOKEN = 'refresh_token'
27+
CLIENT_ID = 'client_id'
28+
CLIENT_SECRET = 'client_secret'
29+
30+
@pytest.fixture(autouse=True)
31+
def credentials(self):
32+
self.credentials = credentials.Credentials(
33+
token=None, refresh_token=self.REFRESH_TOKEN,
34+
token_uri=self.TOKEN_URI, client_id=self.CLIENT_ID,
35+
client_secret=self.CLIENT_SECRET)
36+
37+
def test_default_state(self):
38+
assert not self.credentials.valid
39+
# Expiration hasn't been set yet
40+
assert not self.credentials.expired
41+
# Scopes aren't required for these credentials
42+
assert not self.credentials.requires_scopes
43+
44+
def test_create_scoped(self):
45+
with pytest.raises(NotImplementedError):
46+
self.credentials.with_scopes(['email'])
47+
48+
@mock.patch('google.oauth2._client.refresh_grant')
49+
@mock.patch(
50+
'google.auth._helpers.utcnow', return_value=datetime.datetime.min)
51+
def test_refresh_success(self, now_mock, refresh_grant_mock):
52+
token = 'token'
53+
expiry = _helpers.utcnow() + datetime.timedelta(seconds=500)
54+
refresh_grant_mock.return_value = (
55+
# Access token
56+
token,
57+
# New refresh token
58+
None,
59+
# Expiry,
60+
expiry,
61+
# Extra data
62+
{})
63+
request_mock = mock.Mock()
64+
65+
# Refresh credentials
66+
self.credentials.refresh(request_mock)
67+
68+
# Check jwt grant call.
69+
refresh_grant_mock.assert_called_with(
70+
request_mock, self.TOKEN_URI, self.REFRESH_TOKEN, self.CLIENT_ID,
71+
self.CLIENT_SECRET)
72+
73+
# Check that the credentials have the token and expiry
74+
assert self.credentials.token == token
75+
assert self.credentials.expiry == expiry
76+
77+
# Check that the credentials are valid (have a token and are not
78+
# expired)
79+
assert self.credentials.valid

0 commit comments

Comments
 (0)