-
Notifications
You must be signed in to change notification settings - Fork 5
/
httpie_oauth2.py
68 lines (53 loc) · 1.75 KB
/
httpie_oauth2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""
OAuth 2.0 Client Credentials Plugin for HTTPie.
"""
import sys
from httpie.plugins import AuthPlugin
from oauthlib.oauth2 import BackendApplicationClient, WebApplicationClient, InsecureTransportError
from requests_oauthlib import OAuth2Session
from requests.auth import HTTPBasicAuth, AuthBase
from httpie.cli import parser
from httpie.context import Environment
__version__ = '0.1.0'
__author__ = 'Brian Demers'
__licence__ = 'BSD'
class OAuth2Plugin(AuthPlugin):
name = 'OAuth 2.0 Client Credentials'
auth_type = 'oauth2'
description = ''
oauth = parser.add_argument_group(title='OAuth 2.0')
oauth.add_argument(
'--issuer-uri',
default=None,
metavar='ISSUER_URI',
help="""
The OAuth 2.0 Issuer URI
""",
)
oauth.add_argument(
'--scope',
default=None,
metavar='SCOPE',
help="""
The OAuth 2.0 Scopes
""",
)
def get_auth(self, username, password):
args = parser.args
auth = HTTPBasicAuth(username, password)
client = BackendApplicationClient(client_id=username)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url=args.issuer_uri, auth=auth, scope=args.scope)
return BearerAuth(token=token['access_token'])
class BearerAuth(AuthBase):
"""Adds proof of authorization (Bearer token) to the request."""
def __init__(self, token):
"""Construct a new Bearer authorization object.
:param token: bearer token to attach to request
"""
self.token = token
def __call__(self, r):
"""Append an Bearer header to the request.
"""
r.headers['Authorization'] = 'Bearer %s' % self.token
return r