Skip to content

Commit 3b40159

Browse files
authored
Merge pull request #123 from ringcentral/Oauth-Client-Credential
Add OAuth client credentials support
2 parents 980033a + 9cb4d60 commit 3b40159

8 files changed

Lines changed: 358 additions & 29 deletions

File tree

‎README.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,20 @@ res = platform.get('/account/~/extension/~')
4242
print('User loaded ' + res.json().name)
4343
```
4444

45+
### Client credentials
46+
47+
For an app configured for the OAuth client credentials grant, call `login()` with
48+
no arguments. Call `login()` again when the access token expires.
49+
50+
```py
51+
from ringcentral import SDK
52+
53+
platform = SDK('CLIENT_ID', 'CLIENT_SECRET', 'SERVER').platform()
54+
platform.login()
55+
account = platform.get('/restapi/v2/accounts/~').json_dict()
56+
print(account['id'])
57+
```
58+
4559

4660
## Subscribing for server events
4761

‎api_test/_oauth_smoke.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import json
2+
import os
3+
4+
from dotenv import load_dotenv
5+
6+
from ringcentral.http.api_exception import ApiException
7+
8+
9+
def load_user_config(*extra_required):
10+
load_dotenv()
11+
names = ('RC_SERVER_URL', 'RC_CLIENT_ID', 'RC_CLIENT_SECRET', *extra_required)
12+
values = tuple(os.getenv(name) for name in names)
13+
missing = [name for name, value in zip(names, values) if not value]
14+
if missing:
15+
raise SystemExit(f'Set {", ".join(missing)} in .env or export them in your shell.')
16+
return values
17+
18+
19+
def run_smoke(platform, flow, login):
20+
operation = f'{flow} login'
21+
try:
22+
login()
23+
operation = 'Account lookup'
24+
response = platform.get('/restapi/v2/accounts/~')
25+
account = response.json_dict()
26+
except ApiException as error:
27+
http_response = error.api_response().response()
28+
status = f' (HTTP {http_response.status_code})' if http_response is not None else ''
29+
raise SystemExit(f'{operation} failed{status}.') from None
30+
except Exception as error:
31+
raise SystemExit(f'{operation} failed ({type(error).__name__}).') from None
32+
33+
if not isinstance(account, dict) or not account.get('id'):
34+
raise SystemExit('The account response did not contain an account ID.')
35+
36+
status = response.response().status_code
37+
print(f'{flow} login succeeded. Account lookup returned HTTP {status}.')
38+
print(json.dumps(account, indent=2))

‎api_test/auth_code_smoke.py‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import os
2+
from base64 import urlsafe_b64encode
3+
from hashlib import sha256
4+
from http.server import BaseHTTPRequestHandler, HTTPServer
5+
from secrets import token_urlsafe
6+
from time import monotonic
7+
from urllib.parse import parse_qs, urlsplit
8+
9+
from ringcentral import SDK
10+
11+
from ._oauth_smoke import load_user_config, run_smoke
12+
13+
14+
DEFAULT_REDIRECT_URI = 'http://localhost:5000/oauth2callback'
15+
16+
17+
def get_authorization_code(platform, redirect_uri, challenge):
18+
invalid_redirect = f'Set RC_REDIRECT_URI to a registered HTTP loopback URL with a port, such as {DEFAULT_REDIRECT_URI}.'
19+
try:
20+
callback = urlsplit(redirect_uri)
21+
port = callback.port
22+
except ValueError:
23+
raise SystemExit(invalid_redirect) from None
24+
25+
if (callback.scheme != 'http' or callback.hostname not in ('localhost', '127.0.0.1')
26+
or not port or callback.username is not None or callback.query or callback.fragment):
27+
raise SystemExit(invalid_redirect)
28+
29+
state = token_urlsafe(32)
30+
login_url = platform.login_url(redirect_uri, state=state, challenge=challenge)
31+
code = None
32+
33+
class CallbackHandler(BaseHTTPRequestHandler):
34+
timeout = 5
35+
36+
def do_GET(self):
37+
nonlocal code
38+
target = urlsplit(self.path)
39+
if target.path != (callback.path or '/'):
40+
self.send_error(404)
41+
return
42+
43+
params = parse_qs(target.query, keep_blank_values=True)
44+
if params.get('state') != [state]:
45+
self.send_error(400, 'OAuth state did not match. Open the URL printed in the terminal.')
46+
return
47+
48+
codes = params.get('code', [])
49+
if 'error' in params or len(codes) != 1 or not codes[0]:
50+
code = ''
51+
self.send_error(400, 'Authorization failed. See the terminal for the smoke test result.')
52+
return
53+
54+
code = codes[0]
55+
self.send_response(200)
56+
self.send_header('Content-Type', 'text/plain; charset=utf-8')
57+
self.end_headers()
58+
self.wfile.write(b'Authorization received. Return to the terminal for the smoke test result.')
59+
60+
def log_message(self, format, *args):
61+
# The request line contains the authorization code.
62+
pass
63+
64+
try:
65+
server = HTTPServer(('127.0.0.1', port), CallbackHandler)
66+
except OSError:
67+
raise SystemExit(f'Could not start the authorization callback on port {port}.') from None
68+
69+
with server:
70+
print(f'Open this URL in your browser and authorize the app.\n{login_url}', flush=True)
71+
deadline = monotonic() + 300
72+
while code is None:
73+
server.timeout = deadline - monotonic()
74+
if server.timeout <= 0:
75+
raise SystemExit('Timed out waiting for the authorization callback.')
76+
server.handle_request()
77+
78+
if not code:
79+
raise SystemExit('The authorization callback did not return a usable authorization code.')
80+
return code
81+
82+
83+
def main():
84+
server, client_id, client_secret = load_user_config()
85+
redirect_uri = os.getenv('RC_REDIRECT_URI') or DEFAULT_REDIRECT_URI
86+
platform = SDK(client_id, client_secret, server, redirect_uri=redirect_uri).platform()
87+
88+
def login():
89+
verifier = token_urlsafe(32)
90+
challenge = urlsafe_b64encode(sha256(verifier.encode('ascii')).digest()).decode('ascii').rstrip('=')
91+
code = get_authorization_code(platform, redirect_uri, challenge)
92+
platform.login(code=code, verifier=verifier)
93+
94+
run_smoke(platform, 'Authorization-code', login)
95+
96+
97+
if __name__ == '__main__':
98+
main()
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import os
2+
3+
from dotenv import load_dotenv
4+
5+
from ringcentral import SDK
6+
7+
from ._oauth_smoke import run_smoke
8+
9+
10+
def main():
11+
load_dotenv()
12+
server = os.getenv('RINGCENTRAL_SERVER_URL')
13+
client_id = os.getenv('RINGCENTRAL_CLIENT_ID')
14+
client_secret = os.getenv('RINGCENTRAL_CLIENT_SECRET')
15+
if not all((server, client_id, client_secret)):
16+
raise SystemExit(
17+
'Set RINGCENTRAL_SERVER_URL, RINGCENTRAL_CLIENT_ID, and '
18+
'RINGCENTRAL_CLIENT_SECRET in .env or export them in your shell.'
19+
)
20+
21+
platform = SDK(client_id, client_secret, server).platform()
22+
run_smoke(platform, 'Client credentials', platform.login)
23+
24+
25+
if __name__ == '__main__':
26+
main()

‎api_test/jwt_smoke.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from ringcentral import SDK
2+
3+
from ._oauth_smoke import load_user_config, run_smoke
4+
5+
6+
def main():
7+
server, client_id, client_secret, jwt = load_user_config('RC_JWT')
8+
platform = SDK(client_id, client_secret, server).platform()
9+
run_smoke(platform, 'JWT', lambda: platform.login(jwt=jwt))
10+
11+
12+
if __name__ == '__main__':
13+
main()

‎dev-notes.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,42 @@ uv sync --locked
9393

9494
Unit tests, including the WebSocket subscription tests, use mocks. They are deterministic and require no RingCentral credentials.
9595

96+
## Run the OAuth smoke tests
97+
98+
Each test gets an access token, calls `GET /restapi/v2/accounts/~`, and prints the
99+
HTTP status and account JSON. The test fails if the response has no account ID.
100+
Use an app configured for the grant you are testing and authorized to read account details.
101+
102+
### Client credentials
103+
104+
Copy `.env.sample` to `.env` and set `RINGCENTRAL_SERVER_URL`,
105+
`RINGCENTRAL_CLIENT_ID`, and `RINGCENTRAL_CLIENT_SECRET` for a client credentials
106+
app with access to `GET /restapi/v2/accounts/~`. You can also export the variables
107+
in your shell.
108+
109+
```
110+
uv run --locked python -m api_test.client_credentials_smoke
111+
```
112+
113+
### JWT and authorization code
114+
115+
These tests use the same environment variables as the JavaScript SDK smoke tests.
116+
Set `RC_SERVER_URL`, `RC_CLIENT_ID`, and `RC_CLIENT_SECRET` in `.env` or export them
117+
in your shell. For the JWT test, also set `RC_JWT` to the JWT for your JWT-enabled app.
118+
119+
```
120+
uv run --locked python -m api_test.jwt_smoke
121+
```
122+
123+
For the authorization-code test, use the authorization-code app's client ID and
124+
secret. Register `http://localhost:5000/oauth2callback` as a redirect URI for the
125+
app, or set `RC_REDIRECT_URI` to another registered HTTP loopback URL with an explicit
126+
port. Open the URL printed by the command and approve the request in your browser.
127+
128+
```
129+
uv run --locked python -m api_test.auth_code_smoke
130+
```
131+
96132
## Run demos
97133

98134
Copy `.env.sample` to `.env`.

‎ringcentral/platform/platform.py‎

Lines changed: 30 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import sys
22
try:
3+
import urllib.parse
34
from urllib.parse import urlparse
45
except ImportError:
56
from urlparse import urlparse
@@ -144,7 +145,8 @@ def login_url(self, redirect_uri, state='', challenge='', challenge_method='S256
144145

145146
def login(self, username='', extension='', password='', code='', redirect_uri='', jwt='', verifier=''):
146147
"""
147-
Logs in the user using various authentication methods.
148+
Authenticates a user or application. Call without arguments to use the
149+
client ID and secret configured on the SDK for the client credentials grant.
148150
149151
Args:
150152
username (str, optional): The username for authentication. Required if password is provided. Default is ''.
@@ -162,7 +164,8 @@ def login(self, username='', extension='', password='', code='', redirect_uri=''
162164
Exception: If the login attempt fails or invalid parameters are provided.
163165
164166
Note:
165-
- This method supports multiple authentication flows including password-based, authorization code, and JWT.
167+
- This method supports password, authorization code, JWT, and client credentials grants.
168+
- Call `login()` again when a client credentials token expires.
166169
- It checks for the presence of required parameters and raises an exception if necessary.
167170
- Deprecation warning is issued for username-password login; recommend using JWT or OAuth instead.
168171
- Constructs the appropriate request body based on the provided parameters.
@@ -171,37 +174,47 @@ def login(self, username='', extension='', password='', code='', redirect_uri=''
171174
- Triggers the loginSuccess or loginError event based on the outcome of the login attempt.
172175
"""
173176
try:
174-
if not code and not username and not password and not jwt:
175-
raise Exception('Either code, or username with password, or jwt has to be provided')
176177
if username and password:
177178
warnings.warn("username-password login will soon be deprecated. Please use jwt or OAuth instead.")
178-
if not code and not jwt:
179-
body = {
180-
'grant_type': 'password',
181-
'username': username,
182-
'password': password,
183-
'access_token_ttl': ACCESS_TOKEN_TTL,
184-
'refresh_token_ttl': REFRESH_TOKEN_TTL
185-
}
186-
if extension:
187-
body['extension'] = extension
188-
elif jwt:
179+
if jwt:
189180
body = {
190181
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
191182
'assertion': jwt
192183
}
193-
else:
184+
elif code:
194185
body = {
195186
'grant_type': 'authorization_code',
196187
'redirect_uri': redirect_uri if redirect_uri else self._redirect_uri,
197188
'code': code
198189
}
199190
if verifier:
200191
body['code_verifier'] = verifier
192+
elif username or password:
193+
body = {
194+
'grant_type': 'password',
195+
'username': username,
196+
'password': password,
197+
'access_token_ttl': ACCESS_TOKEN_TTL,
198+
'refresh_token_ttl': REFRESH_TOKEN_TTL
199+
}
200+
if extension:
201+
body['extension'] = extension
202+
elif extension or redirect_uri or verifier:
203+
raise Exception('Either code, or username with password, or jwt has to be provided')
204+
else:
205+
if not self._key or not self._secret:
206+
raise ValueError('Client credentials login requires a client ID and client secret')
207+
body = {'grant_type': 'client_credentials'}
201208

202209
built_url = self.create_url( TOKEN_ENDPOINT, add_server=True )
203210
response = self._request_token( built_url, body=body)
204-
self._auth.set_data(response.json_dict())
211+
auth_data = response.json_dict()
212+
if body['grant_type'] == 'client_credentials':
213+
if not isinstance(auth_data, dict) or not auth_data.get('access_token'):
214+
raise ValueError('Malformed OAuth response: missing access token')
215+
# Use fresh defaults so stored user credentials are cleared on success.
216+
auth_data = Auth().set_data(auth_data).data()
217+
self._auth.set_data(auth_data)
205218
self.trigger(Events.loginSuccess, response)
206219
return response
207220
except Exception as e:

0 commit comments

Comments
 (0)