Python get access token
60 Python code examples are found related to "
get access token".
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: iamporter.py From pyconkr-2015 with MIT License | 10 votes |
def get_access_token(api_key, api_secret): url = 'https://api.iamport.kr/users/getToken' response = requests.post(url, data=dict( imp_key=api_key, imp_secret=api_secret, )) if response.status_code != 200: raise IOError # TODO # TODO : validate expire time result = response.json() if result['code'] is not 0: raise IamporterError(result['code'], result['message']) return result['response']['access_token']
Example 2
Source File: oauth.py From bii-server with MIT License | 9 votes |
def get_access_token(self, code): payload = {'client_id': BII_GOOGLE_OAUTH_CLIENT_ID, 'client_secret': BII_GOOGLE_OAUTH_CLIENT_SECRET, 'code': code, 'grant_type': 'authorization_code', 'redirect_uri': BII_OAUTH_CONTROLLER_URL} headers = {'Accept': 'application/json'} res = requests.post('https://www.googleapis.com/oauth2/v3/token', params=payload, headers=headers) json = res.json() if "error" in json: raise BiiException(json["error"]) return json["access_token"]
Example 3
Source File: oidc_profile.py From django-keycloak with MIT License | 8 votes |
def get_active_access_token(oidc_profile): """ Give access_token and refresh when required. :param django_keycloak.models.KeycloakOpenIDProfile openid_profile: :rtype: string :raise: django_keycloak.services.exceptions.TokensExpired """ initiate_time = timezone.now() if oidc_profile.refresh_expires_before is None \ or initiate_time > oidc_profile.refresh_expires_before: raise TokensExpired() if initiate_time > oidc_profile.expires_before: # Refresh token token_response = oidc_profile.realm.client.openid_api_client\ .refresh_token(refresh_token=oidc_profile.refresh_token) oidc_profile = update_tokens(token_model=oidc_profile, token_response=token_response, initiate_time=initiate_time) return oidc_profile.access_token
Example 4
Source File: trakt_interface.py From trakt-scrobbler with GNU General Public License v2.0 | 8 votes |
def get_access_token(): global token_data if not token_data: token_data = read_json(TRAKT_TOKEN_PATH) if not token_data: logger.info("Access token not found in config. " "Initiating device authentication.") token_data = device_auth() write_json(token_data, TRAKT_TOKEN_PATH) elif token_data['created_at'] + token_data['expires_in'] - \ time.time() < 86400: logger.info("Access token about to expire. Refreshing.") token_data = refresh_token(token_data) write_json(token_data, TRAKT_TOKEN_PATH) if not token_data: logger.error("Unable to get access token. " f"Try deleting {TRAKT_TOKEN_PATH!s} and retry.") notify("Failed to authorize application.", stdout=True) sys.exit(1) return token_data['access_token']
Example 5
Source File: apps.py From gidgethub with Apache License 2.0 | 7 votes |
def get_installation_access_token( gh: GitHubAPI, *, installation_id: str, app_id: str, private_key: str ) -> Dict[str, Any]: """Obtain a GitHub App's installation access token. Return a dictionary containing access token and expiration time. (https://developer.github.com/v3/apps/#create-a-new-installation-token) """ access_token_url = f"/app/installations/{installation_id}/access_tokens" token = get_jwt(app_id=app_id, private_key=private_key) response = await gh.post( access_token_url, data=b"", jwt=token, accept="application/vnd.github.machine-man-preview+json", ) # example response # { # "token": "v1.1f699f1069f60xxx", # "expires_at": "2016-07-11T22:14:10Z" # } return cast(Dict[str, Any], response)
Example 6
Source File: odata.py From ewm-cloud-robotics with Apache License 2.0 | 6 votes |
def get_access_token(self) -> None: """Authenticate at OAuth token endpoint.""" cls = self.__class__ headers = {'Accept': 'application/json'} body = {'client_id': self._config.clientid, 'client_secret': self._config.clientsecret} resp = requests.post( self._config.tokenendpoint, headers=headers, data=body, timeout=cls.TIMEOUT, auth=(self._config.clientid, self._config.clientsecret)) if resp.status_code == 200: resp_dict = resp.json() self._access_token = resp_dict.get('access_token') self._token_type = resp_dict.get('token_type') self.auth_error = False # Add a 1 minute buffer for token expiration self._token_expires = time.time() + resp_dict.get('expires_in') - 60 else: msg = 'Unable to get access token, status code: {}'.format(resp.status_code) _LOGGER.error(msg) raise requests.RequestException(msg)
Example 7
Source File: __init__.py From direct-access-py with MIT License | 6 votes |
def get_access_token(self): """ Get an access token from /tokens endpoint. Automatically sets the Authorization header on the class instance's session. Raises DAAuthException on error :return: token response as dict """ url = self.url + "/tokens" if not self.api_key or not self.client_id or not self.client_secret: raise DAAuthException( "API_KEY, CLIENT_ID and CLIENT_SECRET are required to generate an access token" ) self.session.headers["Authorization"] = "Basic {}".format( base64.b64encode( ":".join([self.client_id, self.client_secret]).encode() ).decode() ) self.session.headers["Content-Type"] = "application/x-www-form-urlencoded" payload = {"grant_type": "client_credentials"} response = self.session.post(url, params=payload) self.logger.debug("Token response: " + json.dumps(response.json(), indent=2)) self.access_token = response.json()["access_token"] self.session.headers["Authorization"] = "bearer {}".format(self.access_token) return response.json()
Example 8
Source File: instagram.py From flask-thirdLogin-demo with MIT License | 6 votes |
def Get_Access_Token(code): ''' Authorization Code cannot repeat ''' Get_Access_Token_Url = Splice(scheme="https", netloc="api.instagram.com", path="/oauth/access_token", query={"client_id": INSTAGRAM_APP_ID, "client_secret": INSTAGRAM_APP_KEY, "code": code, "redirect_uri": REDIRECT_URI}).geturl access_token_data = requests.post(Get_Access_Token_Url, timeout=timeout, verify=verify, proxies=proxies).json() """ { "access_token": "fb2e77d.47a0479900504cb3ab4a1f626d174d2d", "user": { "id": "1574083", "username": "snoopdogg", "full_name": "Snoop Dogg", "profile_picture": "..." } } """ if isinstance(access_token_data, dict): return access_token_data else: raise ServerError("Get Access Token Error with Authorization Code")
Example 9
Source File: github.py From services-to-wordcloud with MIT License | 6 votes |
def get_access_token(self, code, state=None): ''' In callback url: http://host/callback?code=123&state=xyz use code and state to get an access token. ''' kw = dict(client_id=self._client_id, client_secret=self._client_secret, code=code) if self._redirect_uri: kw['redirect_uri'] = self._redirect_uri if state: kw['state'] = state opener = build_opener(HTTPSHandler) request = Request('https://github.com/login/oauth/access_token', data=_encode_params(kw)) request.get_method = _METHOD_MAP['POST'] request.add_header('Accept', 'application/json') try: response = opener.open(request, timeout=TIMEOUT) r = _parse_json(response.read()) if 'error' in r: raise ApiAuthError(str(r.error)) return str(r.access_token) except HTTPError as e: raise ApiAuthError('HTTPError when get access token')
Example 10
Source File: client.py From django-keycloak with MIT License | 6 votes |
def get_access_token(client): """ Get access token from client's service account. :param django_keycloak.models.Client client: :rtype: str """ oidc_profile = get_service_account_profile(client=client) try: return django_keycloak.services.oidc_profile.get_active_access_token( oidc_profile=oidc_profile) except TokensExpired: token_reponse, initiate_time = get_new_access_token(client=client) oidc_profile = django_keycloak.services.oidc_profile.update_tokens( token_model=oidc_profile, token_response=token_reponse, initiate_time=initiate_time ) return oidc_profile.access_token
Example 11
Source File: api.py From python-wink with MIT License | 6 votes |
def get_local_control_access_token(local_control_id): _LOGGER.debug("Local_control_id: %s", local_control_id) if CLIENT_ID and CLIENT_SECRET and REFRESH_TOKEN: data = { "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "grant_type": "refresh_token", "refresh_token": REFRESH_TOKEN, "scope": "local_control", "local_control_id": local_control_id } headers = { 'Content-Type': 'application/json' } response = requests.post('{}/oauth2/token'.format(WinkApiInterface.BASE_URL), data=json.dumps(data), headers=headers) _LOGGER.debug('%s', response) response_json = response.json() access_token = response_json.get('access_token') return access_token _LOGGER.error("Failed to get local control access, reverting to online API") disable_local_control() return None
Example 12
Source File: app_identity_service_pb.py From python-compat-runtime with Apache License 2.0 | 6 votes |
def GetAccessToken(self, request, rpc=None, callback=None, response=None): """Make a GetAccessToken RPC call. Args: request: a GetAccessTokenRequest instance. rpc: Optional RPC instance to use for the call. callback: Optional final callback. Will be called as callback(rpc, result) when the rpc completes. If None, the call is synchronous. response: Optional ProtocolMessage to be filled in with response. Returns: The GetAccessTokenResponse if callback is None. Otherwise, returns None. """ if response is None: response = GetAccessTokenResponse return self._MakeCall(rpc, self._full_name_GetAccessToken, 'GetAccessToken', request, response, callback, self._protorpc_GetAccessToken, package_name='apphosting')
Example 13
Source File: backend.py From boss-oidc with Apache License 2.0 | 6 votes |
def get_access_token(request): """Retrieve access token from the request The access token is searched first the request's session. If it is not found it is then searched in the request's ``Authorization`` header. Args: request (Request): Django request from the user Returns: dict: JWT payload of the bearer token """ access_token = request.session.get("access_token") if access_token is None: # Bearer token login access_token = get_authorization_header(request).split()[1] return JWT().unpack(access_token).payload()
Example 14
Source File: helpers.py From Domoticz-Google-Assistant with Apache License 2.0 | 6 votes |
def get_access_token(self): """Generates a signed JSON Web Token using a Google API Service Account.""" signed_jwt = self.generate_jwt(os.path.join(FILE_DIR, KEYFILE)) if signed_jwt is None: return False url = HOMEGRAPH_TOKEN_URL headers = {'Content-Type': 'application/x-www-form-urlencoded'} data = 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=' + signed_jwt.decode( 'utf-8') r = requests.post(url, headers=headers, data=data) if r.status_code == requests.codes.ok: token_data = json.loads(r.text) self._access_token = token_data['access_token'] return token_data['access_token'] r.raise_for_status() return
Example 15
Source File: docker-registry-sync.py From openshift-toolkit with Apache License 2.0 | 6 votes |
def get_registry_access_token(registry_name, challenge_url, remote_registry_auth_json_file=None): if remote_registry_auth_json_file: auth_config_location = remote_registry_auth_json_file else: from os.path import expanduser user_home_dir = expanduser("~") auth_config_location = "%s/.docker/config.json" % user_home_dir if not auth_config_location: print(auth_config_location) print("Unable to find and read config.json for authentication. " "Did you performed 'docker login' or supply auth file?") sys.exit(1) else: with open(auth_config_location) as auth_data: reg_auth_json_data = json.load(auth_data) reg_upstream_auth_user_token = reg_auth_json_data['auths'][registry_name]['auth'] try: auth_session = requests.Session() auth_header = {'Authorization': 'Basic %s' % reg_upstream_auth_user_token} get_auth_token = auth_session.get(challenge_url, headers=auth_header) parse_get_resp = json.loads(get_auth_token.text) reg_upstream_access_token = parse_get_resp['access_token'] return reg_upstream_access_token except ValueError as e: return e
Example 16
Source File: oauth.py From facebook-insights with ISC License | 6 votes |
def get_access_token(self, code, *vargs, **kwargs): long_term = kwargs.get('long_term', False) if 'long_term' in kwargs: del kwargs['long_term'] data = dict( code=code, grant_type='authorization_code', redirect_uri=self.redirect_uri, ) data.update(kwargs.get('data', {})) kwargs['data'] = data token = super(OAuth2Service, self).get_access_token( *vargs, **kwargs) if long_term: token = self.get_long_term_token(token) return token
Example 17
Source File: get_access_token.py From pyrobotlab with Apache License 2.0 | 6 votes |
def get_access_token(): data = urllib.urlencode({ 'client_id' : client_id, 'client_secret' : client_secret, 'grant_type' : 'client_credentials', 'scope' : 'http://api.microsofttranslator.com' }) try: request = urllib2.Request('https://datamarket.accesscontrol.windows.net/v2/OAuth2-13') request.add_data(data) response = urllib2.urlopen(request) response_data = json.loads(response.read()) if response_data.has_key('access_token'): return response_data['access_token'] except urllib2.URLError, e: if hasattr(e, 'reason'): print datestring(), 'Could not connect to the server:', e.reason elif hasattr(e, 'code'): print datestring(), 'Server error: ', e.code
Example 18
Source File: wechat.py From wego with Apache License 2.0 | 6 votes |
def get_global_access_token(self): """ 获取全局 access token """ def create_group(self, name): """ Create a user group. :param name: Group name. :return: Raw data that wechat returns. """ access_token = self.settings.GET_GLOBAL_ACCESS_TOKEN(self) data = { 'group': { 'name': name } } url = 'https://api.weixin.qq.com/cgi-bin/groups/create?access_token=%s' + access_token data = requests.post(url, data=json.dumps(data)).json() return data
Example 19
Source File: wechat.py From wego with Apache License 2.0 | 6 votes |
def get_access_token(self, code): """ Use code for get access token, refresh token, openid etc. :param code: A code see function get_code_url. :return: Raw data that wechat returns. """ data = requests.get('https://api.weixin.qq.com/sns/oauth2/access_token', params={ 'appid': self.settings.APP_ID, 'secret': self.settings.APP_SECRET, 'code': code, 'grant_type': 'authorization_code' }).json() return data
Example 20
Source File: GitHub.py From content with MIT License | 6 votes |
def get_installation_access_token(installation_id: str, jwt_token: str): """ Get an access token for the given installation id. POSTs https://api.github.com/app/installations/<installation_id>/access_tokens :param installation_id: str: the id of the installation (where the bot was installed) :param jwt_token: str token needed in the request for retrieving the access token """ response = requests.post( "{}/app/installations/{}/access_tokens".format( BASE_URL, installation_id ), headers={ "Authorization": "Bearer {}".format(jwt_token), "Accept": MEDIA_TYPE_INTEGRATION_PREVIEW, }, ) if response.status_code == 201: return response.json()['token'] elif response.status_code == 403: return_error('403 Forbidden - The credentials are incorrect') elif response.status_code == 404: return_error('404 Not found - Installation wasn\'t found') else: return_error(f'Encountered an error: {response.text}')
Example 21
Source File: feed_token_client.py From azure-devops-cli-extension with MIT License | 6 votes |
def get_personal_access_token(self, feed_name=None, token_type=None): """GetPersonalAccessToken. [Preview API] Get a time-limited session token representing the current user, with permissions scoped to the read/write of Artifacts. :param str feed_name: :param str token_type: Type of token to retrieve (e.g. 'SelfDescribing', 'Compact'). :rtype: object """ route_values = {} if feed_name is not None: route_values['feedName'] = self._serialize.url('feed_name', feed_name, 'str') query_parameters = {} if token_type is not None: query_parameters['tokenType'] = self._serialize.query('token_type', token_type, 'str') response = self._send(http_method='GET', location_id='dfdb7ad7-3d8e-4907-911e-19b4a8330550', version='5.0-preview.1', route_values=route_values, query_parameters=query_parameters) return self._deserialize('object', response)
Example 22
Source File: wx_api.py From Archery with Apache License 2.0 | 6 votes |
def get_wx_access_token(): # 优先获取缓存 try: token = cache.get('wx_access_token') except Exception as e: logger.error(f"获取企业微信token缓存出错:{e}") token = None if token: return token # 请求企业微信接口获取 sys_config = SysConfig() corp_id = sys_config.get('wx_corpid') corp_secret = sys_config.get('wx_app_secret') url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={corp_secret}" resp = requests.get(url, timeout=3).json() if resp.get('errcode') == 0: access_token = resp.get('access_token') expires_in = resp.get('expires_in') cache.set('wx_access_token', access_token, timeout=expires_in - 60) return access_token else: logger.error(f"获取企业微信access_token出错:{resp}") return None
Example 23
Source File: credentials_utils.py From googleapps-message-recall with Apache License 2.0 | 6 votes |
def GetUserAccessToken(user_email, force_refresh=False): """Helper to get a refreshed access_token for a user via service account. Args: user_email: User email for which access_token will be retrieved. force_refresh: Boolean, if True force a token refresh. Returns: Cached access_token or a new one. """ access_token = memcache.get(user_email, namespace=_CACHE_NAMESPACE) if access_token and not force_refresh: return access_token credentials = _GetSignedJwtAssertionCredentials(user_email) # Have observed the following error from refresh(): # 'Unable to fetch URL: https://accounts.google.com/o/oauth2/token' _LOG.debug('Refreshing access token for %s.', user_email) credentials.refresh(http_utils.GetHttpObject()) access_token = credentials.access_token if memcache.set(user_email, access_token, time=_ACCESS_TOKEN_CACHE_S, namespace=_CACHE_NAMESPACE): return access_token raise recall_errors.MessageRecallCounterError( 'Exceeded retry limit in GetUserAccessToken: %s.' % user_email)
Example 24
Source File: auth.py From pheme-twitter-conversation-collection with Apache License 2.0 | 6 votes |
def get_xauth_access_token(self, username, password): """ Get an access token from an username and password combination. In order to get this working you need to create an app at http://twitter.com/apps, after that send a mail to api@twitter.com and request activation of xAuth for it. """ try: url = self._get_oauth_url('access_token', secure=True) # must use HTTPS request = oauth.OAuthRequest.from_consumer_and_token( oauth_consumer=self._consumer, http_method='POST', http_url=url, parameters = { 'x_auth_mode': 'client_auth', 'x_auth_username': username, 'x_auth_password': password } ) request.sign_request(self._sigmethod, self._consumer, None) resp = urlopen(Request(url, data=request.to_postdata())) self.access_token = oauth.OAuthToken.from_string(resp.read()) return self.access_token except Exception, e: raise TweepError(e)
Example 25
Source File: auth.py From pheme-twitter-conversation-collection with Apache License 2.0 | 6 votes |
def get_access_token(self, verifier=None): """ After user has authorized the request token, get access token with user supplied verifier. """ try: url = self._get_oauth_url('access_token') # build request request = oauth.OAuthRequest.from_consumer_and_token( self._consumer, token=self.request_token, http_url=url, verifier=str(verifier) ) request.sign_request(self._sigmethod, self._consumer, self.request_token) # send request resp = urlopen(Request(url, headers=request.to_header())) self.access_token = oauth.OAuthToken.from_string(resp.read()) return self.access_token except Exception, e: raise TweepError(e)
Example 26
Source File: ding_api.py From Archery with Apache License 2.0 | 6 votes |
def get_access_token(): """获取access_token:https://ding-doc.dingtalk.com/doc#/serverapi2/eev437""" # 优先获取缓存 try: access_token = rs.execute_command(f"get ding_access_token") except Exception as e: logger.error(f"获取钉钉access_token缓存出错:{e}") access_token = None if access_token: return access_token.decode() # 请求钉钉接口获取 sys_config = SysConfig() app_key = sys_config.get('ding_app_key') app_secret = sys_config.get('ding_app_secret') url = f"https://oapi.dingtalk.com/gettoken?appkey={app_key}&appsecret={app_secret}" resp = requests.get(url, timeout=3).json() if resp.get('errcode') == 0: access_token = resp.get('access_token') expires_in = resp.get('expires_in') rs.execute_command(f"SETEX ding_access_token {expires_in-60} {access_token}") return access_token else: logger.error(f"获取钉钉access_token出错:{resp}") return None
Example 27
Source File: config.py From weixin_server with MIT License | 6 votes |
def get_access_token_function(): access_token = cache.get(WEIXIN_ACCESS_TOKEN_CACHE_KEY) access_token_expires_at = cache.get(WEIXIN_ACCESS_TOKEN_EXPIRES_AT_CACHE_KEY) if not access_token or not access_token_expires_at: response = requests.get( url="https://api.weixin.qq.com/cgi-bin/token", params={ "grant_type": "client_credential", "appid": settings.WEIXIN_APP_ID, "secret": settings.WEIXIN_APP_SECRET, } ) response_json = response.json() access_token = response_json['access_token'] access_token_expires_at = int(time.time()) + response_json['expires_in'] set_access_token_function(access_token, access_token_expires_at) return access_token, access_token_expires_at
Example 28
Source File: oauth2.py From spotipy with MIT License | 6 votes |
def get_access_token(self, state=None, response=None, check_cache=True): """ Gets Auth Token from cache (preferred) or user interaction Parameters ---------- * state: May be given, overrides (without changing) self.state * response: URI with token, can break expiration checks * check_cache: Interpreted as boolean """ if check_cache: token_info = self.get_cached_token() if not (token_info is None or is_token_expired(token_info)): return token_info["access_token"] if response: token_info = self.parse_response_token(response) else: token_info = self.get_auth_response(state) token_info = self._add_custom_values_to_token_info(token_info) self._save_token_info(token_info) return token_info["access_token"]
Example 29
Source File: views.py From wagalytics with MIT License | 6 votes |
def get_access_token(ga_key_filepath): """Get the access token for Google Analytics. from https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/ Defines a method to get an access token from the credentials object. The access token is automatically refreshed if it has expired. """ # The scope for the OAuth2 request. SCOPE = 'https://www.googleapis.com/auth/analytics.readonly' # Construct a credentials objects from the key data and OAuth2 scope. _credentials = ServiceAccountCredentials.from_json_keyfile_name( ga_key_filepath, SCOPE) return _credentials.get_access_token().access_token
Example 30
Source File: service_account.py From aqua-monitor with GNU Lesser General Public License v3.0 | 6 votes |
def get_access_token(self, http=None, additional_claims=None): """Create a signed jwt. Args: http: unused additional_claims: dict, additional claims to add to the payload of the JWT. Returns: An AccessTokenInfo with the signed jwt """ if additional_claims is None: if self.access_token is None or self.access_token_expired: self.refresh(None) return AccessTokenInfo(access_token=self.access_token, expires_in=self._expires_in()) else: # Create a 1 time token token, unused_expiry = self._create_token(additional_claims) return AccessTokenInfo(access_token=token, expires_in=self._MAX_TOKEN_LIFETIME_SECS)
Example 31
Source File: base.py From django-connected with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_access_token(self, request, callback=None): """Fetch access token from callback request.""" raw_token = request.session.get(self.session_key, None) verifier = request.GET.get('oauth_verifier', None) if raw_token is not None and verifier is not None: data = {'oauth_verifier': verifier} callback = request.build_absolute_uri(callback or request.path) callback = force_text(callback) try: response = self.request( 'post', self.access_token_url, token=raw_token, data=data, oauth_callback=callback) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch access token: {0}'.format(e)) return None else: return response.text return None
Example 32
Source File: auth.py From xcube with MIT License | 6 votes |
def get_access_token(self, require_auth: bool = False) -> Optional[str]: """Obtains the access token from the Authorization Header """ # noinspection PyUnresolvedReferences auth = self.request.headers.get("Authorization", None) if not auth: if require_auth: raise ServiceAuthError("Authorization header missing", log_message="Authorization header is expected") return None parts = auth.split() if parts[0].lower() != "bearer": raise ServiceAuthError("Invalid header", log_message='Authorization header must start with "Bearer"') elif len(parts) == 1: raise ServiceAuthError("Invalid header", log_message="Bearer token not found") elif len(parts) > 2: raise ServiceAuthError("Invalid header", log_message="Authorization header must be Bearer token") return parts[1]
Example 33
Source File: service_account.py From jarvis with GNU General Public License v2.0 | 6 votes |
def get_access_token(self, http=None, additional_claims=None): """Create a signed jwt. Args: http: unused additional_claims: dict, additional claims to add to the payload of the JWT. Returns: An AccessTokenInfo with the signed jwt """ if additional_claims is None: if self.access_token is None or self.access_token_expired: self.refresh(None) return client.AccessTokenInfo( access_token=self.access_token, expires_in=self._expires_in()) else: # Create a 1 time token token, unused_expiry = self._create_token(additional_claims) return client.AccessTokenInfo( access_token=token, expires_in=self._MAX_TOKEN_LIFETIME_SECS)
Example 34
Source File: oauth2.py From plugin.audio.spotify with GNU General Public License v3.0 | 6 votes |
def get_access_token(self, code): """ Gets the access token for the app given the code Parameters: - code - the response code """ payload = {'redirect_uri': self.redirect_uri, 'code': code, 'grant_type': 'authorization_code'} if self.scope: payload['scope'] = self.scope if self.state: payload['state'] = self.state headers = self._make_authorization_headers() response = requests.post(self.OAUTH_TOKEN_URL, data=payload, headers=headers, verify=True, proxies=self.proxies) if response.status_code is not 200: raise SpotifyOauthError(response.reason) token_info = response.json() token_info = self._add_custom_values_to_token_info(token_info) self._save_token_info(token_info) return token_info
Example 35
Source File: drf.py From mozilla-django-oidc with Mozilla Public License 2.0 | 6 votes |
def get_access_token(self, request): """ Get the access token based on a request. Returns None if no authentication details were provided. Raises AuthenticationFailed if the token is incorrect. """ header = authentication.get_authorization_header(request) if not header: return None header = header.decode(authentication.HTTP_HEADER_ENCODING) auth = header.split() if auth[0].lower() != 'bearer': return None if len(auth) == 1: msg = 'Invalid "bearer" header: No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid "bearer" header: Credentials string should not contain spaces.' raise exceptions.AuthenticationFailed(msg) return auth[1]
Example 36
Source File: facebook.py From django-simple-forum with MIT License | 6 votes |
def get_access_token_from_code(code, redirect_uri, app_id, app_secret): args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret, } # We would use GraphAPI.request() here, except for that the fact # that the response is a key-value pair, and not JSON. response = urllib2.urlopen("https://graph.facebook.com/oauth/access_token" + "?" + urllib.parse.urlencode(args)).read().decode('utf-8') query_str = parse_qs(response) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] return result else: jsonResponse = json.loads(str(response)) # response = json.loads(response) encoding = response.info().get_content_charset('utf8') data = json.loads(response.read().decode(encoding)) return data
Example 37
Source File: facebook.py From django-simple-forum with MIT License | 6 votes |
def get_app_access_token(app_id, app_secret): # Get an app access token args = {'grant_type': 'client_credentials', 'client_id': app_id, 'client_secret': app_secret} file = urllib2.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args)) try: result = file.read().split("=")[1] finally: file.close() return result
Example 38
Source File: auth.py From fabric8-analytics-server with Apache License 2.0 | 6 votes |
def get_access_token(service_name): """Return the access token for service.""" services = {'github': 'https://github.com'} url = '{auth_url}/api/token?for={service}'.format( auth_url=AUTH_URL, service=services.get(service_name)) token = request.headers.get('Authorization') headers = {"Authorization": token} try: _response = get(url, headers=headers) if _response.status_code == 200: response = _response.json() return {"access_token": response.get('access_token')} else: return {"access_token": None} except Exception: current_app.logger.error("Unable to connect to Auth service")
Example 39
Source File: tinder_token.py From Deep-Learning-Tinder with MIT License | 6 votes |
def get_access_token(email, password): s = robobrowser.RoboBrowser(user_agent=MOBILE_USER_AGENT, parser="lxml") s.open(FB_AUTH) f = s.get_form() f["pass"] = password f["email"] = email s.submit_form(f) f = s.get_form() try: s.submit_form(f, submit=f.submit_fields['__CONFIRM__']) # print(s.response.content.decode()) access_token = re.search(r"access_token=([\w\d]+)", s.response.content.decode()).groups()[0] except requests.exceptions.InvalidSchema as browserAddress: # print(type(browserAddress)) access_token = re.search(r"access_token=([\w\d]+)", str(browserAddress)).groups()[0] return access_token
Example 40
Source File: request_util.py From alexa-skills-kit-sdk-for-python with Apache License 2.0 | 6 votes |
def get_api_access_token(handler_input): # type: (HandlerInput) -> AnyStr """Return the api access token in the request. The method retrieves the ``apiAccessToken`` from the input request, which has the encapsulated information of permissions granted by the user. This token can be used to call Alexa-specific APIs. More information about this can be found here : https://developer.amazon.com/docs/custom-skills/request-and-response-json-reference.html#system-object The SDK already includes this token in the API calls done through the `service_client_factory` in :py:class:`ask_sdk_core.handler_input.HandlerInput`. :param handler_input: The handler input instance that is generally passed in the sdk's request and exception components :type handler_input: ask_sdk_core.handler_input.HandlerInput :return: Api access token from the input request, which encapsulates any permissions consented by the user :rtype: str """ return handler_input.request_envelope.context.system.api_access_token
Example 41
Source File: __init__.py From flask-oidc with BSD 2-Clause "Simplified" License | 6 votes |
def get_access_token(self): """Method to return the current requests' access_token. :returns: Access token or None :rtype: str .. versionadded:: 1.2 """ try: credentials = OAuth2Credentials.from_json( self.credentials_store[g.oidc_id_token['sub']]) return credentials.access_token except KeyError: logger.debug("Expired ID token, credentials missing", exc_info=True) return None
Example 42
Source File: githubpy.py From osint-scraper with MIT License | 6 votes |
def get_access_token(self, code, state=None): ''' In callback url: http://host/callback?code=123&state=xyz use code and state to get an access token. ''' kw = dict(client_id=self._client_id, client_secret=self._client_secret, code=code) if self._redirect_uri: kw['redirect_uri'] = self._redirect_uri if state: kw['state'] = state opener = build_opener(HTTPSHandler) request = Request('https://github.com/login/oauth/access_token', data=_encode_params(kw)) request.get_method = _METHOD_MAP['POST'] request.add_header('Accept', 'application/json') try: response = opener.open(request, timeout=TIMEOUT) r = _parse_json(response.read()) if 'error' in r: raise ApiAuthError(str(r.error)) return str(r.access_token) except HTTPError as e: raise ApiAuthError('HTTPError when get access token')
Example 43
Source File: service.py From pledgeservice with Apache License 2.0 | 6 votes |
def get_access_token(self, method='POST', decoder=parse_utf8_qsl, key='access_token', **kwargs): ''' Returns an access token. :param method: A string representation of the HTTP method to be used, defaults to `POST`. :type method: str :param decoder: A function used to parse the Response content. Should return a dictionary. :type decoder: func :param key: The key the access token will be decoded by, defaults to 'access_token'. :type string: :param \*\*kwargs: Optional arguments. Same as Requests. :type \*\*kwargs: dict ''' r = self.get_raw_access_token(method, **kwargs) access_token, = process_token_request(r, decoder, key) return access_token
Example 44
Source File: facebook.py From django-sitemessage with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_page_access_token(self, app_id, app_secret, user_token): """Returns a dictionary of never expired page token indexed by page names. :param str app_id: Application ID :param str app_secret: Application secret :param str user_token: User short-lived token :rtype: dict """ url_extend = ( self._url_base + '/oauth/access_token?grant_type=fb_exchange_token&' 'client_id=%(app_id)s&client_secret=%(app_secret)s&fb_exchange_token=%(user_token)s') response = self.get(url_extend % {'app_id': app_id, 'app_secret': app_secret, 'user_token': user_token}) user_token_long_lived = response.split('=')[-1] json = self.get(self._url_versioned + '/me/accounts?access_token=%s' % user_token_long_lived, json=True) tokens = {item['name']: item['access_token'] for item in json['data'] if item.get('access_token')} return tokens
Example 45
Source File: vkontakte.py From django-sitemessage with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_access_token(self, *, app_id: str) -> str: """Return an URL to get access token. Opens browser, trying to redirect to a page from location URL of which one can extract access_token (see the messenger class docstring). :param app_id: Application ID. """ url = ( 'https://oauth.vk.com/authorize?' 'client_id=%(app_id)s&' 'scope=wall,offline&' 'display=page&' 'response_type=token&' 'v=%(api_version)s&' 'redirect_uri=https://oauth.vk.com/blank.html' ) % {'app_id': app_id, 'api_version': self._api_version} import webbrowser webbrowser.open(url) return url
Example 46
Source File: oauth2.py From accesslink-example-python with MIT License | 6 votes |
def get_access_token(self, authorization_code): """Exchange authorization code for an access token""" headers = { "Content-Type" : "application/x-www-form-urlencoded", "Accept" : "application/json;charset=UTF-8" } data = { "grant_type" : "authorization_code", "code" : authorization_code } return self.post(endpoint=None, url=self.access_token_url, data=data, headers=headers)
Example 47
Source File: request_util.py From alexa-skills-kit-sdk-for-python with Apache License 2.0 | 6 votes |
def get_account_linking_access_token(handler_input): # type: (HandlerInput) -> Optional[AnyStr] """Return the access token in the request. The method retrieves the user's ``accessToken`` from the input request. Once a user successfully enables a skill and links their Alexa account to the skill, the input request will have the user's access token. A `None` value is returned if there is no access token in the input request. More information on this can be found here : https://developer.amazon.com/docs/account-linking/add-account-linking-logic-custom-skill.html :param handler_input: The handler input instance that is generally passed in the sdk's request and exception components :type handler_input: ask_sdk_core.handler_input.HandlerInput :return: User account linked access token if available. None if not available :rtype: Optional[str] """ return handler_input.request_envelope.context.system.user.access_token
Example 48
Source File: __init__.py From Tautulli with GNU General Public License v3.0 | 6 votes |
def get_access_token_from_code( self, code, redirect_uri, app_id, app_secret): """Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """ args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret} return self.request( "{0}/oauth/access_token".format(self.version), args)
Example 49
Source File: __init__.py From Tautulli with GNU General Public License v3.0 | 6 votes |
def get_app_access_token(self, app_id, app_secret, offline=False): """ Get the application's access token as a string. If offline=True, use the concatenated app ID and secret instead of making an API call. <https://developers.facebook.com/docs/facebook-login/ access-tokens#apptokens> """ if offline: return "{0}|{1}".format(app_id, app_secret) else: args = {'grant_type': 'client_credentials', 'client_id': app_id, 'client_secret': app_secret} return self.request("{0}/oauth/access_token".format(self.version), args=args)["access_token"]
Example 50
Source File: id.py From pajbot with MIT License | 6 votes |
def get_app_access_token(self, scope=[]): response = self.post( "/oauth2/token", { "client_id": self.client_credentials.client_id, "client_secret": self.client_credentials.client_secret, "grant_type": "client_credentials", "scope": (" ".join(scope)), }, ) # response = # { # "access_token": "xxxxxxxxxxxxxxxxxxxxxxxxx", # "expires_in": 5350604, # "token_type": "bearer" # } return AppAccessToken.from_api_response(response)
Example 51
Source File: AuthorizationHelpers.py From Cura with GNU Lesser General Public License v3.0 | 6 votes |
def getAccessTokenUsingRefreshToken(self, refresh_token: str) -> "AuthenticationResponse": """Request the access token from the authorization server using a refresh token. :param refresh_token: :return: An AuthenticationResponse object. """ Logger.log("d", "Refreshing the access token.") data = { "client_id": self._settings.CLIENT_ID if self._settings.CLIENT_ID is not None else "", "redirect_uri": self._settings.CALLBACK_URL if self._settings.CALLBACK_URL is not None else "", "grant_type": "refresh_token", "refresh_token": refresh_token, "scope": self._settings.CLIENT_SCOPES if self._settings.CLIENT_SCOPES is not None else "", } try: return self.parseTokenResponse(requests.post(self._token_url, data = data)) # type: ignore except requests.exceptions.ConnectionError: return AuthenticationResponse(success=False, err_message="Unable to connect to remote server")
Example 52
Source File: certificate_app_credentials.py From botbuilder-python with MIT License | 6 votes |
def get_access_token(self, force_refresh: bool = False) -> str: """ Implementation of AppCredentials.get_token. :return: The access token for the given certificate. """ # Firstly, looks up a token from cache # Since we are looking for token for the current app, NOT for an end user, # notice we give account parameter as None. auth_token = self.__get_msal_app().acquire_token_silent( self.scopes, account=None ) if not auth_token: # No suitable token exists in cache. Let's get a new one from AAD. auth_token = self.__get_msal_app().acquire_token_for_client( scopes=self.scopes ) return auth_token["access_token"]
Example 53
Source File: oauth2api.py From ebay-oauth-python-client with Apache License 2.0 | 6 votes |
def get_access_token(self, env_type, refresh_token, scopes): """ refresh token call """ logging.info("Trying to get a new user access token ... ") credential = credentialutil.get_credentials(env_type) headers = model.util._generate_request_headers(credential) body = model.util._generate_refresh_request_body(' '.join(scopes), refresh_token) resp = requests.post(env_type.api_endpoint, data=body, headers=headers) content = json.loads(resp.content) token = oAuth_token() token.token_response = content if resp.status_code == requests.codes.ok: token.access_token = content['access_token'] token.token_expiry = datetime.utcnow()+timedelta(seconds=int(content['expires_in']))-timedelta(minutes=5) else: token.error = str(resp.status_code) + ': ' + content['error_description'] logging.error("Unable to retrieve token. Status code: %s - %s", resp.status_code, requests.status_codes._codes[resp.status_code]) logging.error("Error: %s - %s", content['error'], content['error_description']) return token
Example 54
Source File: AuthorizationService.py From Cura with GNU Lesser General Public License v3.0 | 6 votes |
def getAccessToken(self) -> Optional[str]: """Get the access token as provided by the repsonse data.""" if self._auth_data is None: Logger.log("d", "No auth data to retrieve the access_token from") return None # Check if the current access token is expired and refresh it if that is the case. # We have a fallback on a date far in the past for currently stored auth data in cura.cfg. received_at = datetime.strptime(self._auth_data.received_at, TOKEN_TIMESTAMP_FORMAT) \ if self._auth_data.received_at else datetime(2000, 1, 1) expiry_date = received_at + timedelta(seconds = float(self._auth_data.expires_in or 0) - 60) if datetime.now() > expiry_date: self.refreshAccessToken() return self._auth_data.access_token if self._auth_data else None
Example 55
Source File: auth.py From twitter-stock-recommendation with MIT License | 6 votes |
def get_xauth_access_token(self, username, password): """ Get an access token from an username and password combination. In order to get this working you need to create an app at http://twitter.com/apps, after that send a mail to api@twitter.com and request activation of xAuth for it. """ try: url = self._get_oauth_url('access_token') oauth = OAuth1(self.consumer_key, client_secret=self.consumer_secret) r = requests.post(url=url, auth=oauth, headers={'x_auth_mode': 'client_auth', 'x_auth_username': username, 'x_auth_password': password}) credentials = parse_qs(r.content) return credentials.get('oauth_token')[0], credentials.get('oauth_token_secret')[0] except Exception as e: raise TweepError(e)
Example 56
Source File: nintendo-switch.py From personal-influxdb with Apache License 2.0 | 5 votes |
def get_access_token(): response = requests.post('https://accounts.nintendo.com/connect/1.0.0/api/token', data={ 'session_token': SESSION_TOKEN, 'client_id': CLIENT_ID, 'grant_type': GRANT_TYPE }) return response.json()
Example 57
Source File: client.py From python-upwork with Apache License 2.0 | 5 votes |
def get_access_token(self, verifier): """Returns access token and access token secret :param verifier: """ try: request_token = self.request_token request_token_secret = self.request_token_secret except AttributeError as e: raise Exception( "Request token pair not found. You need to call get_authorization_url" ) oauth = OAuth1( self.config.consumer_key, client_secret=self.config.consumer_secret, resource_owner_key=self.request_token, resource_owner_secret=self.request_token_secret, verifier=verifier, ) access_token_url = full_url(self.__uri_atoken, upwork.DEFAULT_EPOINT) try: r = requests.post(url=access_token_url, auth=oauth) except Exception as e: raise e atoken_response = dict(parse_qsl(r.content.decode("utf8"))) self.config.access_token = atoken_response.get("oauth_token") self.config.access_token_secret = atoken_response.get("oauth_token_secret") return self.config.access_token, self.config.access_token_secret