Python jwt.algorithms() Examples
The following are 11
code examples of jwt.algorithms().
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.
You may also want to check out all available functions/classes of the module
jwt
, or try the search function
.
Example #1
Source File: validator.py From django-cognito-jwt with MIT License | 9 votes |
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
Example #2
Source File: keycloak.py From vitrage with Apache License 2.0 | 6 votes |
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)
Example #3
Source File: jwt_token_extractor.py From botbuilder-python with MIT License | 5 votes |
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)
Example #4
Source File: jwt_token_extractor.py From botbuilder-python with MIT License | 5 votes |
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
Example #5
Source File: auth.py From xcube with MIT License | 5 votes |
def __init__(self, domain: str, audience: str, algorithms: List[str]): self._domain = domain self._audience = audience self._algorithms = algorithms
Example #6
Source File: auth.py From xcube with MIT License | 5 votes |
def algorithms(self) -> List[str]: return self._algorithms
Example #7
Source File: auth.py From xcube with MIT License | 5 votes |
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)
Example #8
Source File: keycloak.py From vitrage with Apache License 2.0 | 5 votes |
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)
Example #9
Source File: synapse_oauth2.py From fence with Apache License 2.0 | 4 votes |
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)}
Example #10
Source File: msbot.py From microsoftbotframework with MIT License | 4 votes |
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
Example #11
Source File: msbot.py From microsoftbotframework with MIT License | 4 votes |
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