def test_override_configs(self): self.app.config['JWT_TOKEN_LOCATION'] = 'cookies' self.app.config['JWT_HEADER_NAME'] = 'Auth' self.app.config['JWT_HEADER_TYPE'] = 'JWT' self.app.config['JWT_COOKIE_SECURE'] = True self.app.config['JWT_ACCESS_COOKIE_NAME'] = 'banana1' self.app.config['JWT_REFRESH_COOKIE_NAME'] = 'banana2' self.app.config['JWT_ACCESS_COOKIE_PATH'] = '/banana/' self.app.config['JWT_REFRESH_COOKIE_PATH'] = '/banana2/' self.app.config['JWT_COOKIE_CSRF_PROTECT'] = False self.app.config['JWT_ACCESS_CSRF_COOKIE_NAME'] = 'banana1a' self.app.config['JWT_REFRESH_CSRF_COOKIE_NAME'] = 'banana2a' self.app.config['JWT_CSRF_HEADER_NAME'] = 'bananaaaa' self.app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(minutes=5) self.app.config['JWT_REFRESH_TOKEN_EXPIRES'] = timedelta(days=7) self.app.config['JWT_ALGORITHM'] = 'HS512' self.app.config['JWT_BLACKLIST_ENABLED'] = True self.app.config['JWT_BLACKLIST_STORE'] = simplekv.memory.DictStore() self.app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = 'all' with self.app.test_request_context(): self.assertEqual(get_token_location(), 'cookies') self.assertEqual(get_jwt_header_name(), 'Auth') self.assertEqual(get_jwt_header_type(), 'JWT') self.assertEqual(get_cookie_secure(), True) self.assertEqual(get_access_cookie_name(), 'banana1') self.assertEqual(get_refresh_cookie_name(), 'banana2') self.assertEqual(get_access_cookie_path(), '/banana/') self.assertEqual(get_refresh_cookie_path(), '/banana2/') self.assertEqual(get_cookie_csrf_protect(), False) self.assertEqual(get_access_csrf_cookie_name(), 'banana1a') self.assertEqual(get_refresh_csrf_cookie_name(), 'banana2a') self.assertEqual(get_csrf_header_name(), 'bananaaaa') self.assertEqual(get_access_expires(), timedelta(minutes=5)) self.assertEqual(get_refresh_expires(), timedelta(days=7)) self.assertEqual(get_algorithm(), 'HS512') self.assertEqual(get_blacklist_enabled(), True) self.assertIsInstance(get_blacklist_store(), simplekv.memory.DictStore) self.assertEqual(get_blacklist_checks(), 'all') self.app.config['JWT_TOKEN_LOCATION'] = 'banana' self.app.config['JWT_HEADER_NAME'] = '' self.app.config['JWT_ACCESS_TOKEN_EXPIRES'] = 'banana' self.app.config['JWT_REFRESH_TOKEN_EXPIRES'] = 'banana' self.app.testing = True # Propagate exceptions with self.app.test_request_context(): with self.assertRaises(RuntimeError): get_jwt_header_name() with self.assertRaises(RuntimeError): get_access_expires() with self.assertRaises(RuntimeError): get_refresh_expires() with self.assertRaises(RuntimeError): get_token_location()
def create_access_token(identity, fresh=False): """ Creates a new access token :param identity: The identity of this token. This can be any data that is json serializable. It can also be an object, in which case you can use the user_identity_loader to define a function that will be called to pull a json serializable identity out of this object. This is useful so you don't need to query disk twice, once for initially finding the identity in your login endpoint, and once for setting addition data in the JWT via the user_claims_loader :param fresh: If this token should be marked as fresh, and can thus access fresh_jwt_required protected endpoints. Defaults to False :return: A newly encoded JWT access token """ # Token options secret = _get_secret_key() access_expire_delta = get_access_expires() algorithm = get_algorithm() user_claims = current_app.jwt_manager._user_claims_callback(identity) identity = current_app.jwt_manager._user_identity_callback(identity) access_token = _encode_access_token(identity, secret, algorithm, access_expire_delta, fresh=fresh, user_claims=user_claims) return access_token
def _decode_jwt_from_cookies(type): if type == 'access': cookie_key = get_access_cookie_name() else: cookie_key = get_refresh_cookie_name() token = request.cookies.get(cookie_key) if not token: raise NoAuthorizationError('Missing cookie "{}"'.format(cookie_key)) secret = _get_secret_key() algorithm = get_algorithm() token = _decode_jwt(token, secret, algorithm) if get_cookie_csrf_protect( ) and request.method in get_csrf_request_methods(): csrf_header_key = get_csrf_header_name() csrf_token_from_header = request.headers.get(csrf_header_key, None) csrf_token_from_cookie = token.get('csrf', None) # Verify the csrf tokens are present and matching if csrf_token_from_cookie is None: raise JWTDecodeError("Missing claim: 'csrf'") if not isinstance(csrf_token_from_cookie, six.string_types): raise JWTDecodeError("Invalid claim: 'csrf' (must be a string)") if csrf_token_from_header is None: raise CSRFError("Missing CSRF token in headers") if not safe_str_cmp(csrf_token_from_header, csrf_token_from_cookie): raise CSRFError("CSRF double submit tokens do not match") return token
def _decode_jwt_from_headers(): # Verify we have the auth header header_name = get_jwt_header_name() jwt_header = request.headers.get(header_name, None) if not jwt_header: raise NoAuthorizationError("Missing {} Header".format(header_name)) # Make sure the header is valid expected_header = get_jwt_header_type() parts = jwt_header.split() if not expected_header: if len(parts) != 1: msg = "Bad {} header. Expected '<JWT>'" raise InvalidHeaderError(msg) token = parts[0] else: if parts[0] != expected_header or len(parts) != 2: msg = "Bad {} header. Expected '{} <JWT>'".format( header_name, expected_header) raise InvalidHeaderError(msg) token = parts[1] secret = _get_secret_key() algorithm = get_algorithm() return _decode_jwt(token, secret, algorithm)
def create_access_token(identity, fresh=True): # Token options secret = _get_secret_key() access_expire_delta = get_access_expires() algorithm = get_algorithm() user_claims = current_app.jwt_manager.user_claims_callback(identity) access_token = _encode_access_token(identity, secret, algorithm, access_expire_delta, fresh=fresh, user_claims=user_claims) return access_token
def test_default_configs(self): with self.app.test_request_context(): self.assertEqual(get_access_expires(), timedelta(minutes=15)) self.assertEqual(get_refresh_expires(), timedelta(days=30)) self.assertEqual(get_algorithm(), 'HS256') self.assertEqual(get_blacklist_enabled(), False) self.assertEqual(get_blacklist_store(), None) self.assertEqual(get_blacklist_checks(), 'refresh') self.assertEqual(get_auth_header(), 'Bearer')
def create_refresh_token(identity): # Token settings refresh_expire_delta = get_refresh_expires() algorithm = get_algorithm() secret = _get_secret_key() # Actually make the tokens refresh_token = _encode_refresh_token(identity, secret, algorithm, refresh_expire_delta) return refresh_token
def create_refresh_token(identity): # Token settings refresh_expire_delta = get_refresh_expires() algorithm = get_algorithm() secret = _get_secret_key() identity = current_app.jwt_manager._user_identity_callback(identity) # Actually make the tokens refresh_token = _encode_refresh_token(identity, secret, algorithm, refresh_expire_delta) return refresh_token
def wrapper(*args, **kwargs): token = request.args.get('refresh_token') secret = _get_secret_key() algorithm = get_algorithm() jwt_data = _decode_jwt(token, secret, algorithm) if jwt_data['type'] != 'refresh': raise WrongTokenError( 'Only refresh tokens can access this endpoint') ctx_stack.top.jwt = jwt_data return fn(*args, **kwargs)
def test_override_configs(self): self.app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(minutes=5) self.app.config['JWT_REFRESH_TOKEN_EXPIRES'] = timedelta(days=7) self.app.config['JWT_ALGORITHM'] = 'HS512' self.app.config['JWT_BLACKLIST_ENABLED'] = True self.app.config['JWT_BLACKLIST_STORE'] = simplekv.memory.DictStore() self.app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = 'all' self.app.config['JWT_AUTH_HEADER'] = 'JWT' with self.app.test_request_context(): self.assertEqual(get_access_expires(), timedelta(minutes=5)) self.assertEqual(get_refresh_expires(), timedelta(days=7)) self.assertEqual(get_algorithm(), 'HS512') self.assertEqual(get_blacklist_enabled(), True) self.assertIsInstance(get_blacklist_store(), simplekv.memory.DictStore) self.assertEqual(get_blacklist_checks(), 'all') self.assertEqual(get_auth_header(), 'JWT')
def _decode_jwt_from_cookies(type): if type == 'access': cookie_key = get_access_cookie_name() else: cookie_key = get_refresh_cookie_name() token = request.cookies.get(cookie_key) if not token: raise NoAuthorizationError('Missing cookie "{}"'.format(cookie_key)) secret = _get_secret_key() algorithm = get_algorithm() token = _decode_jwt(token, secret, algorithm) if get_cookie_csrf_protect(): csrf_header_key = get_csrf_header_name() csrf = request.headers.get(csrf_header_key, None) if not csrf or not safe_str_cmp(csrf, token['csrf']): raise NoAuthorizationError( "Missing or invalid csrf double submit header") return token
def _decode_jwt_from_request(): # Verify we have the auth header auth_header = request.headers.get('Authorization', None) if not auth_header: raise NoAuthHeaderError("Missing Authorization Header") # Make sure the header is valid expected_header = get_auth_header() parts = auth_header.split() if not expected_header: if len(parts) != 1: msg = "Badly formatted authorization header. Should be '<JWT>'" raise InvalidHeaderError(msg) token = parts[0] else: if parts[0] != expected_header or len(parts) != 2: msg = "Bad authorization header. Expected '{} <JWT>'".format(expected_header) raise InvalidHeaderError(msg) token = parts[1] secret = _get_secret_key() algorithm = get_algorithm() return _decode_jwt(token, secret, algorithm)
def test_default_configs(self): with self.app.test_request_context(): self.assertEqual(get_token_location(), 'headers') self.assertEqual(get_jwt_header_name(), 'Authorization') self.assertEqual(get_jwt_header_type(), 'Bearer') self.assertEqual(get_cookie_secure(), False) self.assertEqual(get_access_cookie_name(), 'access_token_cookie') self.assertEqual(get_refresh_cookie_name(), 'refresh_token_cookie') self.assertEqual(get_access_cookie_path(), None) self.assertEqual(get_refresh_cookie_path(), None) self.assertEqual(get_cookie_csrf_protect(), True) self.assertEqual(get_access_csrf_cookie_name(), 'csrf_access_token') self.assertEqual(get_refresh_csrf_cookie_name(), 'csrf_refresh_token') self.assertEqual(get_csrf_header_name(), 'X-CSRF-TOKEN') self.assertEqual(get_access_expires(), timedelta(minutes=15)) self.assertEqual(get_refresh_expires(), timedelta(days=30)) self.assertEqual(get_algorithm(), 'HS256') self.assertEqual(get_blacklist_enabled(), False) self.assertEqual(get_blacklist_store(), None) self.assertEqual(get_blacklist_checks(), 'refresh')
def _get_csrf_token(encoded_token): secret = _get_secret_key() algorithm = get_algorithm() token = _decode_jwt(encoded_token, secret, algorithm) return token['csrf']