本文整理汇总了Python中jwt.algorithms方法的典型用法代码示例。如果您正苦于以下问题:Python jwt.algorithms方法的具体用法?Python jwt.algorithms怎么用?Python jwt.algorithms使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jwt
的用法示例。
在下文中一共展示了jwt.algorithms方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: call_keycloak
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import algorithms [as 别名]
def call_keycloak(self, token, decoded, audience):
if self.user_info_endpoint_url.startswith(('http://', 'https://')):
endpoint = self.user_info_endpoint_url
self.send_request_to_auth_server(endpoint, token)
else:
public_key = self.get_public_key(self.realm_name(decoded))
try:
if self.keycloak_iss:
self.keycloak_iss = self.keycloak_iss % \
self.realm_name(decoded)
jwt.decode(token, public_key, audience=audience,
issuer=self.keycloak_iss, algorithms=['RS256'],
verify=True)
except Exception:
message = 'Token validation failure'
self._unauthorized(message)
示例2: validate
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import algorithms [as 别名]
def validate(self, token):
public_key = self._get_public_key(token)
if not public_key:
raise TokenError("No key found for this token")
try:
jwt_data = jwt.decode(
token,
public_key,
audience=self.audience,
issuer=self.pool_url,
algorithms=["RS256"],
)
except (jwt.InvalidTokenError, jwt.ExpiredSignature, jwt.DecodeError) as exc:
raise TokenError(str(exc))
return jwt_data
示例3: __init__
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import algorithms [as 别名]
def __init__(
self,
validation_params: VerifyOptions,
metadata_url: str,
allowed_algorithms: list,
):
self.validation_parameters = validation_params
self.validation_parameters.algorithms = allowed_algorithms
self.open_id_metadata = JwtTokenExtractor.get_open_id_metadata(metadata_url)
示例4: _validate_token
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import algorithms [as 别名]
def _validate_token(
self, jwt_token: str, channel_id: str, required_endorsements: List[str] = None
) -> ClaimsIdentity:
required_endorsements = required_endorsements or []
headers = jwt.get_unverified_header(jwt_token)
# Update the signing tokens from the last refresh
key_id = headers.get("kid", None)
metadata = await self.open_id_metadata.get(key_id)
if key_id and metadata.endorsements:
# Verify that channelId is included in endorsements
if not EndorsementsValidator.validate(channel_id, metadata.endorsements):
raise Exception("Could not validate endorsement key")
# Verify that additional endorsements are satisfied.
# If no additional endorsements are expected, the requirement is satisfied as well
for endorsement in required_endorsements:
if not EndorsementsValidator.validate(
endorsement, metadata.endorsements
):
raise Exception("Could not validate endorsement key")
if headers.get("alg", None) not in self.validation_parameters.algorithms:
raise Exception("Token signing algorithm not in allowed list")
options = {
"verify_aud": False,
"verify_exp": not self.validation_parameters.ignore_expiration,
}
decoded_payload = jwt.decode(
jwt_token,
metadata.public_key,
leeway=self.validation_parameters.clock_tolerance,
options=options,
)
claims = ClaimsIdentity(decoded_payload, True)
return claims
示例5: __init__
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import algorithms [as 别名]
def __init__(self, domain: str, audience: str, algorithms: List[str]):
self._domain = domain
self._audience = audience
self._algorithms = algorithms
示例6: algorithms
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import algorithms [as 别名]
def algorithms(self) -> List[str]:
return self._algorithms
示例7: from_config
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import algorithms [as 别名]
def from_config(cls, config: Dict[str, Any]) -> Optional['AuthConfig']:
authentication = config.get('Authentication')
if not authentication:
return None
domain = authentication.get('Domain')
if not domain:
raise ServiceConfigError('Missing key "Domain" in section "Authentication"')
audience = authentication.get('Audience')
if not audience:
raise ServiceConfigError('Missing key "Audience" in section "Authentication"')
algorithms = authentication.get('Algorithms', ['RS256'])
if not algorithms:
raise ServiceConfigError('Value for key "Algorithms" in section "Authentication" must not be empty')
return AuthConfig(domain, audience, algorithms)
示例8: _decode
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import algorithms [as 别名]
def _decode(self, token):
try:
return jwt.decode(token, algorithms=['RS256'], verify=False)
except jwt.DecodeError:
message = "Token can't be decoded because of wrong format."
self._unauthorized(message)
示例9: get_user_id
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import algorithms [as 别名]
def get_user_id(self, code):
try:
token_endpoint = self.get_value_from_discovery_doc(
"token_endpoint", config["SYNAPSE_URI"] + "/oauth2/token"
)
# For testing new Synapse JWKS doc (if pinned to new JWKS doc)
# or avoid downtime (if pinned to old JWKS doc)
# TODO: can be removed after tested with new Synapse JWKS doc
# and Synapse has deployed their changes
if config["SYNAPSE_JWKS_URI"]:
jwks_endpoint = config["SYNAPSE_JWKS_URI"]
else:
jwks_endpoint = self.get_value_from_discovery_doc(
"jwks_uri", config["SYNAPSE_URI"] + "/oauth2/jwks"
)
token = self.get_token(token_endpoint, code)
algorithm, key = self.load_key(jwks_endpoint)
if not key:
return dict(error="Cannot load JWK keys")
claims = jwt.decode(
token["id_token"],
key,
options={"verify_aud": False, "verify_at_hash": False},
algorithms=[algorithm],
)
if not claims["email_verified"]:
return dict(error="Email is not verified")
rv = {}
none = object()
for claim in (
self.REQUIRED_CLAIMS
| self.OPTIONAL_CLAIMS
| self.SYSTEM_CLAIMS
| self.CUSTOM_CLAIMS
):
value = claims.get(claim, none)
if value is none:
if claim not in self.OPTIONAL_CLAIMS:
return dict(error="Required claim {} not found".format(claim))
else:
rv[claim] = value
rv["fence_username"] = rv["userid"] + " (Synapse ID)"
return rv
except Exception as e:
self.logger.exception("Can't get user info")
return {"error": "Can't get ID token: {}".format(e)}
示例10: __init__
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import algorithms [as 别名]
def __init__(self, import_name=None, app_client_id=None, verify_jwt_signature=None,
config_location=None, cache=None, state=None, timeout_seconds=None, *args, **kwargs):
depreciated_host = kwargs.pop('host', None)
depreciated_port = kwargs.pop('port', None)
depreciated_debug = kwargs.pop('debug', None)
if depreciated_debug is not None or depreciated_port is not None or depreciated_host is not None:
raise(Exception('Depreciated: host, port and debug arguments are now passed to the MsBot.run() method.'))
# This is left as a option incase the user wants to extend the MsBot object
name = __name__ if import_name is None else import_name
self.timeout_seconds = timeout_seconds
super().__init__(name, *args, **kwargs)
self.add_url_rule('/api/messages', view_func=self._message_post, methods=['POST'])
self.mbf_config = Config(config_location=config_location)
self.processes = []
self.app_client_id = self.mbf_config.get_config(app_client_id, 'APP_CLIENT_ID')
cache_arg = self.mbf_config.get_config(cache, 'cache')
state_arg = self.mbf_config.get_config(state, 'state')
self.cache_certs = True
try:
from jwt.algorithms import RSAAlgorithm
import jwt
self.verify_jwt_signature = self.mbf_config.get_config(verify_jwt_signature, 'VERIFY_JWT_SIGNATURE')
except ImportError:
self.verify_jwt_signature = False
self.cache_certs = False
self.logger.info('The jwt library\s has not been installed. Disabling certificate caching.')
if (cache_arg is None or not cache_arg) and self.verify_jwt_signature:
self.logger.info('A cache object has not been set. Disabling certificate caching.')
self.cache_certs = False
if self.cache_certs and self.verify_jwt_signature:
self.cache = get_cache(cache_arg, self.mbf_config)
if state_arg is not None:
self.state = get_state(state_arg, self.mbf_config)
else:
self.state = None
示例11: _verify_token
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import algorithms [as 别名]
def _verify_token(self, request, forced_refresh=False):
authorization_header = request.headers['Authorization']
token = authorization_header[7:]
authorization_scheme = authorization_header[:6]
token_headers = jwt.get_unverified_header(token)
# Get valid signing keys
if self.cache_certs:
valid_certificates = self._get_stored_certificates(forced_refresh=forced_refresh)
else:
valid_certificates = self._get_remote_certificates()
# 1. The token was sent in the HTTP Authorization header with 'Bearer' scheme
if authorization_scheme != "Bearer":
self.logger.warning('The token was not sent in the http authorisation header with the Bearer scheme.')
return False
# 2. The token is valid JSON that conforms to the JWT standard (see references)
# 4. The token contains an audience claim with a value equivalent to your bot's Microsoft App ID.
# 5. The token has not yet expired. Industry-standard clock-skew is 5 minutes.
# 6. The token has a valid cryptographic signature with a key listed in the OpenId keys document retrieved in step 1, above.
decoded_jwt = None
for dict_key in valid_certificates['keys']:
if dict_key['kid'] == token_headers['kid']:
key = json.dumps(dict_key)
algo = RSAAlgorithm('SHA256')
public_key = algo.from_jwk(key)
try:
decoded_jwt = jwt.decode(token, public_key, algorithms=['RS256'], audience=self.app_client_id)
except jwt.exceptions.InvalidTokenError as e:
self.logger.warning('{}'.format(e))
if decoded_jwt is None:
if self.cache_certs and not forced_refresh:
# Force cache refresh
self.logger.warning('Forcing cache refresh as no valid certificate was found.')
self._get_remote_certificates()
return self._verify_token(request, forced_refresh=True)
self.logger.warning('No valid certificate was found to verify JWT')
return False
if decoded_jwt is None:
return False
# 3. The token contains an issuer claim with value of https://api.botframework.com
if decoded_jwt['iss'] != 'https://api.botframework.com':
self.logger.warning('The token issuer claim had the incorrect value of {}'.format(decoded_jwt['iss']))
return False
self.logger.info('Token was validated - {}'.format(json.dumps(decoded_jwt)))
return decoded_jwt