def validate_token(token): try: token_body = token.split(" ")[1] except IndexError: raise DecodeError('Bearer token malformed.') payload = jwt_package.decode(token_body, current_app.config.get('SECRET_KEY')) return payload['identity']
def decode(self, jwt: str, key: str = '', verify: bool = True, algorithms: List[str] = None, options: Dict = None, **kwargs): """ :type encrypt_password: str :type encrypt_salt: str """ if verify and not algorithms: warnings.warn( 'It is strongly recommended that you pass in a ' + 'value for the "algorithms" argument when calling decode(). ' + 'This argument will be mandatory in a future version.', DeprecationWarning) password = kwargs.get("encrypt_password", None) if not password: raise ValueError("Invalid encrypt password") salt = kwargs.get("encrypt_salt", None) crypt_payload, _, _, _ = self._load(jwt) payload = fernet_decrypt(crypt_payload, password, salt).decode("UTF-8") if options is None: options = {'verify_signature': verify} else: options.setdefault('verify_signature', verify) try: payload = json.loads(payload) except ValueError as e: raise DecodeError('Invalid payload string: %s' % e) if not isinstance(payload, Mapping): raise DecodeError('Invalid payload string: must be a json object') if verify: merged_options = merge_dict(self.options, options) self._validate_claims(payload, merged_options, **kwargs) return payload
def get_public_key(self, kid): """ Retrieve JWT keys from the URL. """ resp = self.request(self.jwks_url(), method='GET') resp.raise_for_status() # find the proper key for the kid for key in resp.json()['keys']: if key['kid'] == kid: return self.jwt_key_to_pem(key) raise DecodeError('Cannot find kid={}'.format(kid))
def decode(self) -> 'JWTPayload': decoded = jwt.decode( jwt=self.token_string, key=self.encryption_key, algorithms=self.algorithms, verify_exp=True, # verify expiry date ('exp' argument) ) if decoded: return JWTPayload(decoded) else: raise DecodeError('Token could not be decoded.')
def __init__(self, payload: dict): self.dict = payload # required payload try: self.path = payload.get(PATH_KEY) self.user_pk = payload.get(USER_PK_KEY) self.verification_token = payload.get(VERIFICATION_TOKEN_KEY) except KeyError as err: raise DecodeError('Required payload missing from token.', err) # optional payload self.expiry_date = payload.get(EXPIRY_DATE_KEY, None) self.check_path_params = payload.get(CHECK_PATH_PARAMS_KEY, False)
def get_certificate(self, kid): # retrieve keys from jwks_url resp = self.request(self.jwks_url(), method='GET') resp.raise_for_status() # find the proper key for the kid for key in resp.json()['keys']: if key['kid'] == kid: x5c = key['x5c'][0] break else: raise DecodeError(f'Cannot find kid={kid}') return load_der_x509_certificate(base64.b64decode(x5c), default_backend())
def get_certificate(self, kid): # retrieve keys from jwks_url resp = self.request(self.jwks_url(), method='GET') resp.raise_for_status() # find the proper key for the kid for key in resp.json()['keys']: if key['kid'] == kid: x5c = key['x5c'][0] break else: raise DecodeError('Cannot find kid={}'.format(kid)) certificate = '-----BEGIN CERTIFICATE-----\n' \ '{}\n' \ '-----END CERTIFICATE-----'.format(x5c) return load_pem_x509_certificate(certificate.encode(), default_backend())
def claims(self, http_method, url, headers=None, qsh_check_exempt=False): token = self._get_token(headers=headers, query_params=parse_query_params(url)) claims = jwt.decode(token, verify=False, algorithms=self.algorithms, options={"verify_signature": False}) if not qsh_check_exempt and claims['qsh'] != hash_url( http_method, url): raise DecodeError('qsh does not match') # verify shared secret jwt.decode(token, audience=claims.get('aud'), key=self.get_shared_secret(claims['iss']), algorithms=self.algorithms, leeway=self.leeway) return claims
def _unpack(cls, token): if isinstance(token, (str, unicode)): token = token.encode('utf-8') try: signing_input, crypto_segment = token.rsplit(b'.', 1) header_segment, payload_segment = signing_input.split(b'.', 1) except ValueError: raise DecodeError('Not enough segments') try: header_data = base64url_decode(header_segment) except (TypeError, binascii.Error): raise DecodeError('Invalid header padding') try: header = json.loads(header_data.decode('utf-8')) except ValueError as e: raise DecodeError('Invalid header string: %s' % e) if not isinstance(header, Mapping): raise DecodeError('Invalid header string: must be a json object') try: payload_data = base64url_decode(payload_segment) except (TypeError, binascii.Error): raise DecodeError('Invalid payload padding') try: payload = json.loads(payload_data.decode('utf-8')) except ValueError as e: raise DecodeError('Invalid payload string: %s' % e) try: signature = base64url_decode(crypto_segment) except (TypeError, binascii.Error): raise DecodeError('Invalid crypto padding') return (header, payload, signature, signing_input)