Beispiel #1
0
class OAuthAgent(object):
    r"""
    OAuth handler/aide for Application access

    :param str client_id: Client ID code
    :param str client_secret: Client secret code
    :param str token_url: Endpoint for requesting OAuth2 tokens
    """
    def __init__(self, client_id, client_secret, token_url):
        self.client_id = client_id
        self.client = BackendApplicationClient(client_id=self.client_id)
        self.oauth = OAuth2Session(client=self.client)
        self.token_url = token_url
        self.secret = client_secret
        self.fetch_token()

    def fetch_token(self):
        r"""
        Retrieve a new OAuth2 token from the service server
        """
        self.client.prepare_request_body()
        self.token = self.oauth.fetch_token(token_url=self.token_url,
                                            auth=(self.client_id, self.secret))

    @refresh
    def request(self, method, url, **kwargs):
        r"""
        Call `requests.request` internally using OAuth2Session

        :param str method: 'POST', 'GET', etc.
        :param str url: Endpoint
        :params kwargs: Keyword arguments
        :rtype: `requests.request`
        """
        return self.oauth.request(method, url, **kwargs)
Beispiel #2
0
def getAccessToken(param):
    """Fetch access token from B2ACCESS"""
    if param.verbose == True:
        print "\nFetching access token from B2ACCESS"
    """ Pre-req: Create a user 'argo' with password 'test' in group 'oauth-clients' and 'eudat:b2share' or any other """ 
    
    try:
        client = BackendApplicationClient(client_id=username)
        client.prepare_request_body(scope=['USER_PROFILE','GENERATE_USER_CERTIFICATE'])
        oauth = OAuth2Session(client=client)
        token = oauth.fetch_token(token_url=str(param.url)+TOKEN_URI, verify=False,client_id=str(param.username),client_secret=str(param.password),scope=['USER_PROFILE','GENERATE_USER_CERTIFICATE'])
        j = json.dumps(token, indent=4)
        k = json.loads(j)
        if param.verbose:
            print "Access token: "+k['access_token']
        
        getTokenInfo(str(param.url)+'/oauth2/tokeninfo', str(k['access_token']), param.verbose)
        getUserInfo(str(param.url)+'/oauth2/userinfo', str(k['access_token']), param.verbose)
    except ConnectionError as e:
        print "CRITICAL: Invalid Unity URL: {0}".format(e)
        sys.exit(2)
    except MissingTokenError as e:
        print "CRITICAL: Invalid client Id and/or secret: {0}".format(e.description)
        sys.exit(2)
    except TypeError as e:
        print e
        sys.exit(2)
    except:
        print("CRITICAL: Error fetching OAuth 2.0 access token:", sys.exc_info()[0])
        sys.exit(2)
        raise
def getAccessToken(param):
    """Fetch access token from B2ACCESS"""
    if param.verbose == True:
        print "\nFetching access token from B2ACCESS"
    """ Pre-req: Create a user 'argo' with password 'test' in group 'oauth-clients' and 'eudat:b2share' or any other """ 
    
    try:
        client = BackendApplicationClient(client_id=username)
        client.prepare_request_body(scope=['profile','email','GENERATE_USER_CERTIFICATE'])
        oauth = OAuth2Session(client=client)
        token = oauth.fetch_token(token_url=str(param.url)+TOKEN_URI, verify=False,client_id=str(param.username),client_secret=str(param.password),scope=['USER_PROFILE','GENERATE_USER_CERTIFICATE'])
        j = json.dumps(token, indent=4)
        k = json.loads(j)
        if param.verbose:
            print "Access token: "+k['access_token']
        
        getTokenInfo(str(param.url)+'/oauth2/tokeninfo', str(k['access_token']), param.verbose)
        getUserInfo(str(param.url)+'/oauth2/userinfo', str(k['access_token']), param.verbose)
    except ConnectionError as e:
        print "CRITICAL: Invalid Unity URL: {0}".format(e)
        sys.exit(2)
    except MissingTokenError as e:
        print "CRITICAL: Invalid client Id and/or secret: {0}".format(e.description)
        sys.exit(2)
    except TypeError as e:
        print e
        sys.exit(2)
    except:
        print("CRITICAL: Error fetching OAuth 2.0 access token:", sys.exc_info()[0])
        sys.exit(2)
        raise
    def _create_oauth_session(self, client_id, client_secret, verify_ssl=True):

        token_url = '{}/v1/oauth/token'.format(self._server)

        client = BackendApplicationClient(client_id=client_id)
        client.prepare_request_body()
        oauth = TokenReFetcherOAuth2Session(token_url=token_url,
                                            client_secret=client_secret,
                                            client=client,
                                            verify=verify_ssl)

        self._session = oauth
    def test_request_body(self):
        client = BackendApplicationClient(self.client_id)

        # Basic, no extra arguments
        body = client.prepare_request_body(body=self.body)
        self.assertFormBodyEqual(body, self.body_up)

        rclient = BackendApplicationClient(self.client_id)
        body = rclient.prepare_request_body(body=self.body)
        self.assertFormBodyEqual(body, self.body_up)

        # With extra parameters
        body = client.prepare_request_body(body=self.body, **self.kwargs)
        self.assertFormBodyEqual(body, self.body_kwargs)
Beispiel #6
0
    def test_request_body(self):
        client = BackendApplicationClient(self.client_id)

        # Basic, no extra arguments
        body = client.prepare_request_body(body=self.body)
        self.assertFormBodyEqual(body, self.body_up)

        rclient = BackendApplicationClient(self.client_id)
        body = rclient.prepare_request_body(body=self.body)
        self.assertFormBodyEqual(body, self.body_up)

        # With extra parameters
        body = client.prepare_request_body(body=self.body, **self.kwargs)
        self.assertFormBodyEqual(body, self.body_kwargs)
Beispiel #7
0
def create_lumiante_session(tenant_path,
                            client_id,
                            client_secret,
                            verify_ssl_certificate=True):
    token_url = '{}/v1/oauth/token'.format(tenant_path)

    client = BackendApplicationClient(client_id=client_id)
    client.prepare_request_body()
    oauth = TokenReFetcherOAuth2Session(token_url=token_url,
                                        client_secret=client_secret,
                                        client=client,
                                        verify=verify_ssl_certificate)

    return oauth
Beispiel #8
0
from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session

client_id = 'test-key'
client_secret = 'NSbpWeyfCrQR6K9kbpuuTBwsgLrOHtLm'  # SECRET! find a secure place to store, do NOT share

client = BackendApplicationClient(client_id=client_id)
client.prepare_request_body(scope=[])

# fetch an access token
session = OAuth2Session(client=client)
session.fetch_token(token_url='https://auth.weather.mg/oauth/token',
                    client_id=client_id,
                    client_secret=client_secret)

# access tokens are valid for one hour an can be re-used
# print "ACCESS TOKEN (base64 encoded) >>> " + session.access_token

# fetch example observation data
# the OAuth2Session will automatically handle adding authentication headers
params = {
    'locatedAt': '13,52',
    'observedPeriod': 'PT0S',
    'fields': 'airTemperatureInCelsius'
}
data = session.get('https://point-observation.weather.mg/search', params=params)

print "RESPONSE DATA >>> " + data.text