def _decode_jwt_from_request(request_type): # We have three cases here, having jwts in both cookies and headers is # valid, or the jwt can only be saved in one of cookies or headers. Check # all cases here. if config.jwt_in_cookies and config.jwt_in_headers: try: decoded_token = _decode_jwt_from_cookies(request_type) except NoAuthorizationError: try: decoded_token = _decode_jwt_from_headers() except NoAuthorizationError: raise NoAuthorizationError("Missing JWT in headers and cookies") elif config.jwt_in_headers: decoded_token = _decode_jwt_from_headers() else: decoded_token = _decode_jwt_from_cookies(request_type) # Make sure the type of token we received matches the request type we expect if decoded_token['type'] != request_type: raise WrongTokenError('Only {} tokens can access this endpoint'.format(request_type)) # Check if the custom claims in access tokens are valid if request_type == 'access': if not verify_token_claims(decoded_token['user_claims']): raise UserClaimsVerificationError('user_claims verification failed') # If blacklisting is enabled, see if this token has been revoked if _token_blacklisted(decoded_token, request_type): raise RevokedTokenError('Token has been revoked') return decoded_token
def wrapper(*args, **kwargs): jwt_data = _decode_jwt_from_request(request_type='access') ctx_stack.top.jwt = jwt_data if not verify_token_claims(jwt_data[config.user_claims]): raise UserClaimsVerificationError( 'User claims verification failed') _load_user(jwt_data[config.identity_claim]) return fn(*args, **kwargs)
def can_get_available_dates(self) -> bool: allowed_to_access_available_dates = (self.claims.get( "available_dates", {}).get("permissions", {}).get("get_result", False)) if not allowed_to_access_available_dates: raise UserClaimsVerificationError( f"Token does not allow access to available dates.") return True
def wrapper(*args, **kwargs): try: jwt_data = _decode_jwt_from_request(request_type='access') ctx_stack.top.jwt = jwt_data if not verify_token_claims(jwt_data[config.user_claims_key]): raise UserClaimsVerificationError( 'User claims verification failed') _load_user(jwt_data[config.identity_claim_key]) except (NoAuthorizationError, InvalidHeaderError): pass return fn(*args, **kwargs)
def has_access( self, *, action: str, query_kinds_and_aggregations: List[Tuple[str, str]]) -> bool: """ Returns true if the user can do 'action' with this kind of query at this unit of aggregation. Parameters ---------- action: {'run', 'poll', 'get_results'} Action to check query_kinds_and_aggregations : list of tuples List of tuples giving a query kind and aggregation unit Returns ------- bool True if the user can do 'action' with this query Raises ------ UserClaimsVerificationError If the user cannot do action with this kind of query at this level of aggregation """ for query_kind, aggregation_unit in query_kinds_and_aggregations: try: action_rights = self.claims[query_kind]["permissions"][action] aggregation_right = ( aggregation_unit in self.claims[query_kind]["spatial_aggregation"]) if not action_rights: raise UserClaimsVerificationError( f"Token does not allow {action} for query kind '{query_kind}'" ) if not aggregation_right: raise UserClaimsVerificationError( f"Token does not allow query kind '{query_kind}' at spatial aggregation '{aggregation_unit}'" ) except KeyError: raise UserClaimsVerificationError( "Claims verification failed.") return True
def wrapper(*args, **kwargs): jwt_data = _decode_jwt_from_request(request_type='access') ctx_stack.top.jwt = jwt_data fresh = jwt_data['fresh'] if isinstance(fresh, bool): if not fresh: raise FreshTokenRequired('Fresh token required') else: now = timegm(datetime.utcnow().utctimetuple()) if fresh < now: raise FreshTokenRequired('Fresh token required') if not verify_token_claims(jwt_data[config.user_claims_key]): raise UserClaimsVerificationError( 'User claims verification failed') _load_user(jwt_data[config.identity_claim_key]) return fn(*args, **kwargs)
def test_admin_required_with_invalid_jwt(mock_verify_jwt_in_request: Mock, mock_get_jwt_claims: Mock) -> None: called = False @admin_required def function() -> None: nonlocal called called = True mock_verify_jwt_in_request.side_effect = UserClaimsVerificationError( 'error') exception = None try: function() except Exception as e: exception = e mock_verify_jwt_in_request.assert_called_once_with() mock_get_jwt_claims.assert_not_called() assert exception is not None assert isinstance(exception, UserClaimsVerificationError)
def verify_token_claims(jwt_data): jwt_manager = _get_jwt_manager() user_claims = jwt_data[config.user_claims_key] if not jwt_manager._claims_verification_callback(user_claims): raise UserClaimsVerificationError('User claims verification failed')
def custom_verification_for_token(jwt_header, jwt_data): jwt_manager = get_jwt_manager() if not jwt_manager._token_verification_callback(jwt_header, jwt_data): error_msg = "User claims verification failed" raise UserClaimsVerificationError(error_msg, jwt_header, jwt_data)