本文整理汇总了Python中google.auth.transport.requests.Request方法的典型用法代码示例。如果您正苦于以下问题:Python requests.Request方法的具体用法?Python requests.Request怎么用?Python requests.Request使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类google.auth.transport.requests
的用法示例。
在下文中一共展示了requests.Request方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getCreds
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Request [as 别名]
def getCreds():
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
creds = None
SCOPES = 'https://www.googleapis.com/auth/drive'
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
return creds
示例2: logout
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Request [as 别名]
def logout(user_name: str):
"""Logs out the user, removing their stored credentials and revoking the
grant
Args:
user_name (str): The identifier of the user.
"""
store = Store()
user_credentials = store.get_user_credentials(user_name)
if user_credentials is None:
logging.info('Ignoring logout request for user %s', user_name)
return
logging.info('Logging out user %s', user_name)
store.delete_user_credentials(user_name)
request = requests.Request()
request.post(
'https://accounts.google.com/o/oauth2/revoke',
params={'token': user_credentials.token},
headers={'Content-Type': 'application/x-www-form-urlencoded'})
示例3: credentials
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Request [as 别名]
def credentials(self) -> dict:
if self._credentials is None:
if not os.path.exists(self.credentials_path):
raise ValueError(f"{self.credentials_path}: no such file or directory")
if os.path.exists(self.token_path):
with open(self.token_path, "rb") as fp:
self._credentials = pickle.load(fp)
if not self._credentials or not self._credentials.valid:
if self._credentials and self._credentials.expired and self._credentials.refresh_token:
self._credentials.refresh(transport.Request())
else:
flow = oauthflow.InstalledAppFlow.from_client_secrets_file(self.credentials_path, self.scopes)
self._credentials = flow.run_local_server()
with open(self.token_path, "wb") as fp:
pickle.dump(self._credentials, fp)
return self._credentials
示例4: test_default_state
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Request [as 别名]
def test_default_state(self, get):
get.side_effect = [
{"email": "service-account@example.com", "scope": ["one", "two"]}
]
request = mock.create_autospec(transport.Request, instance=True)
self.credentials = credentials.IDTokenCredentials(
request=request, target_audience="https://example.com"
)
assert not self.credentials.valid
# Expiration hasn't been set yet
assert not self.credentials.expired
# Service account email hasn't been populated
assert self.credentials.service_account_email == "service-account@example.com"
# Signer is initialized
assert self.credentials.signer
assert self.credentials.signer_email == "service-account@example.com"
示例5: test_with_service_account
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Request [as 别名]
def test_with_service_account(self, sign, get, utcnow):
sign.side_effect = [b"signature"]
request = mock.create_autospec(transport.Request, instance=True)
self.credentials = credentials.IDTokenCredentials(
request=request,
target_audience="https://audience.com",
service_account_email="service-account@other.com",
)
# Generate authorization grant:
token = self.credentials._make_authorization_grant_assertion()
payload = jwt.decode(token, verify=False)
# The JWT token signature is 'signature' encoded in base 64:
assert token.endswith(b".c2lnbmF0dXJl")
# Check that the credentials have the token and proper expiration
assert payload == {
"aud": "https://www.googleapis.com/oauth2/v4/token",
"exp": 3600,
"iat": 0,
"iss": "service-account@other.com",
"target_audience": "https://audience.com",
}
示例6: test_refresh_error
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Request [as 别名]
def test_refresh_error(self, sign, get, utcnow):
get.side_effect = [
{"email": "service-account@example.com", "scopes": ["one", "two"]}
]
sign.side_effect = [b"signature"]
request = mock.create_autospec(transport.Request, instance=True)
response = mock.Mock()
response.data = b'{"error": "http error"}'
response.status = 500
request.side_effect = [response]
self.credentials = credentials.IDTokenCredentials(
request=request, target_audience="https://audience.com"
)
with pytest.raises(exceptions.RefreshError) as excinfo:
self.credentials.refresh(request)
assert excinfo.match(r"http error")
示例7: test_sign_bytes
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Request [as 别名]
def test_sign_bytes(self, sign, get):
get.side_effect = [
{"email": "service-account@example.com", "scopes": ["one", "two"]}
]
sign.side_effect = [b"signature"]
request = mock.create_autospec(transport.Request, instance=True)
response = mock.Mock()
response.data = b'{"signature": "c2lnbmF0dXJl"}'
response.status = 200
request.side_effect = [response]
self.credentials = credentials.IDTokenCredentials(
request=request, target_audience="https://audience.com"
)
# Generate authorization grant:
signature = self.credentials.sign_bytes(b"some bytes")
# The JWT token signature is 'signature' encoded in base 64:
assert signature == b"signature"
示例8: verify_token
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Request [as 别名]
def verify_token(id_token, request, audience=None, certs_url=_GOOGLE_OAUTH2_CERTS_URL):
"""Verifies an ID token and returns the decoded token.
Args:
id_token (Union[str, bytes]): The encoded token.
request (google.auth.transport.Request): The object used to make
HTTP requests.
audience (str): The audience that this token is intended for. If None
then the audience is not verified.
certs_url (str): The URL that specifies the certificates to use to
verify the token. This URL should return JSON in the format of
``{'key id': 'x509 certificate'}``.
Returns:
Mapping[str, Any]: The decoded token.
"""
certs = _fetch_certs(request, certs_url)
return jwt.decode(id_token, certs=certs, audience=audience)
示例9: verify_firebase_token
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Request [as 别名]
def verify_firebase_token(id_token, request, audience=None):
"""Verifies an ID Token issued by Firebase Authentication.
Args:
id_token (Union[str, bytes]): The encoded token.
request (google.auth.transport.Request): The object used to make
HTTP requests.
audience (str): The audience that this token is intended for. This is
typically your Firebase application ID. If None then the audience
is not verified.
Returns:
Mapping[str, Any]: The decoded token.
"""
return verify_token(
id_token, request, audience=audience, certs_url=_GOOGLE_APIS_CERTS_URL
)
示例10: _check_adc
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Request [as 别名]
def _check_adc():
"""Return whether the application default credential exists and is valid."""
# google-auth wants to warn the user if no project is set, which makes sense
# for cloud-only users, but not in our case. We temporarily chnage the logging
# level here to silence.
logger = _logging.getLogger()
log_level = logger.level
logger.setLevel(_logging.ERROR)
try:
creds, _ = _google_auth.default()
except _google_auth.exceptions.DefaultCredentialsError:
return False
finally:
logger.setLevel(log_level)
transport = _auth_requests.Request()
try:
creds.refresh(transport)
except Exception as e: # pylint:disable=broad-except
_logging.info('Failure refreshing credentials: %s', e)
return creds.valid
示例11: _fetch_certs
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Request [as 别名]
def _fetch_certs(request, certs_url):
"""Fetches certificates.
Google-style cerificate endpoints return JSON in the format of
``{'key id': 'x509 certificate'}``.
Args:
request (google.auth.transport.Request): The object used to make
HTTP requests.
certs_url (str): The certificate endpoint URL.
Returns:
Mapping[str, str]: A mapping of public key ID to x.509 certificate
data.
"""
response = request(certs_url, method='GET')
if response.status != http_client.OK:
raise exceptions.TransportError(
'Could not fetch certificates at {}'.format(certs_url))
return json.loads(response.data.decode('utf-8'))
示例12: verify_token
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Request [as 别名]
def verify_token(id_token, request, audience=None,
certs_url=_GOOGLE_OAUTH2_CERTS_URL):
"""Verifies an ID token and returns the decoded token.
Args:
id_token (Union[str, bytes]): The encoded token.
request (google.auth.transport.Request): The object used to make
HTTP requests.
audience (str): The audience that this token is intended for. If None
then the audience is not verified.
certs_url (str): The URL that specifies the certificates to use to
verify the token. This URL should return JSON in the format of
``{'key id': 'x509 certificate'}``.
Returns:
Mapping[str, Any]: The decoded token.
"""
certs = _fetch_certs(request, certs_url)
return jwt.decode(id_token, certs=certs, audience=audience)
示例13: verify_oauth2_token
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Request [as 别名]
def verify_oauth2_token(id_token, request, audience=None):
"""Verifies an ID Token issued by Google's OAuth 2.0 authorization server.
Args:
id_token (Union[str, bytes]): The encoded token.
request (google.auth.transport.Request): The object used to make
HTTP requests.
audience (str): The audience that this token is intended for. This is
typically your application's OAuth 2.0 client ID. If None then the
audience is not verified.
Returns:
Mapping[str, Any]: The decoded token.
"""
return verify_token(
id_token, request, audience=audience,
certs_url=_GOOGLE_OAUTH2_CERTS_URL)
示例14: verify_firebase_token
# 需要导入模块: from google.auth.transport import requests [as 别名]
# 或者: from google.auth.transport.requests import Request [as 别名]
def verify_firebase_token(id_token, request, audience=None):
"""Verifies an ID Token issued by Firebase Authentication.
Args:
id_token (Union[str, bytes]): The encoded token.
request (google.auth.transport.Request): The object used to make
HTTP requests.
audience (str): The audience that this token is intended for. This is
typically your Firebase application ID. If None then the audience
is not verified.
Returns:
Mapping[str, Any]: The decoded token.
"""
return verify_token(
id_token, request, audience=audience, certs_url=_GOOGLE_APIS_CERTS_URL)