def test_configuration_custom_class_and_config_item_as_method(): app = Sanic("sanic-jwt-test") class MyConfig(Configuration): def set_access_token_name(self): return ConfigItem("config-item-function-level") sanicjwt = Initialize( app, configuration_class=MyConfig, authenticate=lambda: True ) assert sanicjwt.config.access_token_name() == "config-item-function-level"
def test_authentication_subbclass_with_method_in_class(): app = Sanic() sanicjwt = Initialize(app, authentication_class=AuthenticationInClassBody) _, response = app.test_client.post( "/auth", json={"username": "******", "password": "******"} ) assert response.status == 200 assert sanicjwt.config.access_token_name() in response.json
def app_with_retrieve_user_on_bp(authenticate, retrieve_user, app_with_bp_setup_without_init): app, bp = app_with_bp_setup_without_init sanicjwt = Initialize( bp, app=app, authenticate=authenticate, retrieve_user=retrieve_user, debug=True, ) app.blueprint(bp) return app, sanicjwt, bp
def test_configuration_dynamic_config(): app = Sanic() auth_header_key = "x-authorization-header" class MyConfig(Configuration): def get_authorization_header(self, request): if auth_header_key in request.headers: return request.headers.get(auth_header_key) return "authorization" async def authenticate(request, *args, **kwargs): return {"user_id": 1} sanicjwt = Initialize(app, configuration_class=MyConfig, authenticate=authenticate) @app.route("/protected") @sanicjwt.protected() def protected_route(request): return json({"protected": "yes"}) _, response = app.test_client.post("/auth", json={ "username": "******", "password": "******" }) access_token = response.json.get(sanicjwt.config.access_token_name(), None) assert access_token is not None _, response = app.test_client.get( "/protected", headers={ auth_header_key: "foobarbaz", "foobarbaz": "Bearer {}".format(access_token), }, ) assert response.status == 200 assert response.json.get("protected") == "yes" _, response = app.test_client.get( "/protected", headers={ sanicjwt.config.authorization_header(): "Bearer {}".format(access_token) }, ) assert response.status == 200 assert response.json.get("protected") == "yes"
def app_with_refresh_token(username_table, authenticate): sanic_app = Sanic() sanic_jwt = Initialize( sanic_app, authenticate=authenticate, refresh_token_enabled=True, store_refresh_token=lambda user_id, refresh_token, request: True, retrieve_refresh_token=lambda user_id, request: True, ) yield (sanic_app, sanic_jwt)
def test_configuration_initialize_class_as_argument(): app = Sanic("sanic-jwt-test") class MyConfig(Configuration): def set_access_token_name(self): return "return-level" sanicjwt = Initialize( app, configuration_class=MyConfig, authenticate=lambda: True ) assert sanicjwt.config.access_token_name() == "return-level"
def register_blueprints(root: str, app: Sanic) -> None: for name in find_modules(root, recursive=True): mod = import_string(name) if hasattr(mod, 'bp'): if mod.bp.name == 'admin': Initialize(mod.bp, app=app, authenticate=jwt_authenticate, retrieve_user=retrieve_user, store_refresh_token=store_refresh_token, retrieve_refresh_token=retrieve_refresh_token, secret=config.JWT_SECRET, expiration_delta=config.EXPIRATION_DELTA) app.register_blueprint(mod.bp)
def app_with_refresh_token(users, authenticate): cache = {} async def store_refresh_token(user_id, refresh_token, *args, **kwargs): key = "refresh_token_{user_id}".format(user_id=user_id) cache[key] = refresh_token async def retrieve_refresh_token(user_id, *args, **kwargs): key = "refresh_token_{user_id}".format(user_id=user_id) return cache.get(key, None) async def retrieve_user(request, payload, *args, **kwargs): if payload: user_id = payload.get("user_id", None) if user_id is not None: for u in users: if u.user_id == user_id: return u else: return None secret = str(binascii.hexlify(os.urandom(32)), "utf-8") sanic_app = Sanic("sanic-jwt-test") sanicjwt = Initialize( sanic_app, authenticate=authenticate, store_refresh_token=store_refresh_token, retrieve_refresh_token=retrieve_refresh_token, retrieve_user=retrieve_user, query_string_set=True, query_string_strict=True, refresh_token_enabled=True, access_token_name="jwt_access_token", refresh_token_name="jwt_refresh_token", query_string_access_token_name="jwt_access_token", query_string_refresh_token_name="jwt_refresh_token", secret=secret, ) @sanic_app.route("/") async def helloworld(request): return json({"hello": "world"}) @sanic_app.route("/protected") @protected() async def protected_request(request): return json({"protected": True}) yield (sanic_app, sanicjwt)
def test_initialize_with_custom_endpoint_not_subclassed(): class SubclassHTTPMethodView(HTTPMethodView): async def options(self, request): return text('', status=204) async def get(self, request): return text('ok') app = Sanic() with pytest.raises(exceptions.InvalidClassViewsFormat): Initialize(app, authenticate=lambda: True, class_views=[('/subclass', SubclassHTTPMethodView)])
def test_configuration_no_set_secret(): app = Sanic("sanic-jwt-test") with pytest.warns(UserWarning) as record: Initialize(app, authenticate=lambda: True) assert len(record) == 1 assert record[0].message.args[0] == ( "Sanic JWT was initialized using the default secret available to the " "public. DO NOT DEPLOY your application until you change it. " "See https://sanic-jwt.readthedocs.io/en/latest/pages/configuration.html#secret " "for more information." )
def app_with_bp(username_table, authenticate): sanic_app = Sanic() sanic_jwt_init = Initialize( sanic_app, authenticate=authenticate, ) @sanic_app.route("/") async def helloworld(request): return json({"hello": "world"}) @sanic_app.route("/protected") @protected() async def protected_request(request): return json({"protected": True}) sanic_bp = Blueprint('bp', url_prefix='/bp') sanic_app.blueprint(sanic_bp) sanic_jwt_init_bp = Initialize( sanic_bp, app=sanic_app, authenticate=authenticate, ) print('sanic_bp', sanic_bp.url_prefix) print('sanic_jwt_init_bp', sanic_jwt_init_bp._get_url_prefix()) print('sanic_bp', sanic_bp.routes) @sanic_bp.route("/") async def bp_helloworld(request): return json({"hello": "world"}) @sanic_bp.route("/protected") @protected() async def bp_protected_request(request): return json({"protected": True}) yield (sanic_app, sanic_jwt_init, sanic_bp, sanic_jwt_init_bp)
def test_microservice_simple(): microservice_app = Sanic("sanic-jwt-test") Initialize(microservice_app, auth_mode=False) microservice_app.route("/")(lambda _:...) _, response = microservice_app.test_client.post("/auth", json={ "username": "******", "password": "******" }) assert response.status == 404
def test_configuration_with_override(): app = Sanic("sanic-jwt-test") sanicjwt = Initialize( app, authenticate=lambda: True, access_token_name="customtoken" ) assert sanicjwt.config.access_token_name() == "customtoken" with app.auth.override(access_token_name="foobar"): assert sanicjwt.config.access_token_name() == "foobar" assert sanicjwt.config.access_token_name() == "customtoken"
def getapp(): app = Sanic(__name__) # инициализируем sanic-jwt Initialize(app, authenticate=authenticate, url_prefix='/user/auth', auth_mode=True, cookie_set=True, cookie_strict=False) # зарегистрируем экземпляр блюпринта в приложении app.blueprint(bp_user) return app
def config_app(): # # REDIS (refresh_token cache) # config.redis_client = StrictRedis(host="127.0.0.1", port=6379, db=0) # # sanic_jwt configuration & setup # custom_claims = [NameClaim, EmailClaim] Initialize( config.app, authenticate=authenticate, custom_claims=custom_claims, store_refresh_token=store_refresh_token, retrieve_refresh_token=retrieve_refresh_token, retrieve_user=retrieve_user, add_scopes_to_payload=scope_extender, debug=True, claim_iat=True, refresh_token_enabled=True, ) # # user routes # config.app.add_route(register, "/users", methods=["POST"]) config.app.add_route(get_users, "/users", methods=["GET"]) config.app.add_route( update_user_scope, "/users/<userId>/scopes", methods=["PATCH"] ) config.app.add_route(update_user, "/users/<userId>", methods=["PATCH"]) config.app.add_route(delete_user, "/users/<userId>", methods=["DELETE"]) # # jogging routes # config.app.add_route(add_jogging_result, "/results", methods=["POST"]) config.app.add_route( update_jogging_result, "/results/<resultId>", methods=["PATCH"] ) config.app.add_route( get_jogging_result, "/results/<resultId>", methods=["GET"] ) config.app.add_route( delete_jogging_result, "/results/<resultId>", methods=["DELETE"] ) config.app.add_route(get_jogging_results, "/results", methods=["GET"]) config.app.add_route( get_jogging_weekly_report, "/results/reports/weekly", methods=["GET"] )
def test_microservice_interaction(): microservice_app = Sanic("sanic-jwt-test") microservice_sanic_jwt = Initialize(microservice_app, auth_mode=False) @microservice_app.route("/protected") @microservice_sanic_jwt.protected() async def protected_request(request): return json({"protected": True}) app = Sanic("sanic-jwt-test") sanic_jwt = Initialize(app, authenticate=authenticate) _, response = microservice_app.test_client.get("/protected") assert response.status == 401 assert response.json.get("exception") == "Unauthorized" assert "Authorization header not present." in response.json.get("reasons") _, response = app.test_client.post("/auth", json={ "username": "******", "password": "******" }) access_token = response.json.get(sanic_jwt.config.access_token_name(), None) assert response.status == 200 assert access_token is not None _, response = microservice_app.test_client.get( "/protected", headers={"Authorization": "Bearer {}".format(access_token)}, ) assert response.status == 200 assert response.json.get("protected") is True
def initialize_app(app: Sanic, class_views: Tuple = ()) -> None: Initialize( app, authenticate=authenticate, add_scopes_to_payload=scope_extender, extend_payload=payload_extender, class_views=class_views, responses_class=ExtendedResponses, retrieve_user=retrieve_user, algorithm=constants.JWT_METHOD, private_key=config.jwt_private_key, public_key=config.jwt_public_key, url_prefix="/api/auth", user_id="username", )
def test_config_with_cookie_path(users, authenticate): path = "/auth" sanic_app = Sanic("sanic-jwt-test") Initialize( sanic_app, authenticate=authenticate, cookie_set=True, cookie_path=path ) _, response = sanic_app.test_client.post( "/auth", json={"username": "******", "password": "******"}, raw_cookies=True, ) cookie = response.raw_cookies.get("access_token") assert cookie.path == path
def create_app(settings): app = Sanic(__name__, log_config=settings['LOGGING_CONFIG_FILE_HANDLER']) CORS(app, automatic_options=True) app.config.update(**settings) app.config.update({'LOGO': None}) app.blueprint(bp_dog) from app.receiver import on_message_common, on_ad_message from app.temp_receiver import temp_ad_on_message_commom @app.listener('before_server_start') async def before_server_start(_app, _loop): _app.db = await db.init_app(_loop, _app.config['DATABASES']) _app.redis = redis.init_app(_loop, _app.config['REDIS']) _app.client_session = csa.init_session(loop=_loop) # gbot mq connect _app.mq = await sanic_mq.init_app(_loop, _app.config['MQ_CONFIG']) await sanic_mq.channel() await sanic_mq.exchange('gemii.gbot.topic') await sanic_mq.bind_async_receiver('queue.bot.common.dog', 'queue.bot.common.dog', on_message_common) await sanic_mq.bind_async_receiver('queue.bot.common.temp_ad', 'queue.bot.common.temp_ad', temp_ad_on_message_commom) # gdog mq connect _app.inner_mq = await inner_mq.init_app(_loop, _app.config['INNER_MQ_CONFIG']) await inner_mq.channel() await inner_mq.exchange('gemii.gdog.topic') await inner_mq.bind_async_receiver('queue.rs.msg_class', 'queue.rs.msg_class', on_ad_message) @app.listener('after_server_stop') async def after_server_stop(_app, _loop): await _app.client_session.close() await _app.db.close() _app.redis.connection_pool.disconnect() await sanic_mq.disconnection() Initialize(app, authentication_class=CustomAuthentication, responses_class=CustomerResponses, refresh_token_enabled=False, secret=settings['JWT_SECRET'], expiration_delta=1 * 60 * 60) return app
def config_app(): # # DB # from dbhelper import do_engine do_engine() # # REDIS (refresh_token cache) # config.redis_client = StrictRedis(host="127.0.0.1", port=6379, db=0) # # sanic_jwt configuration & setup # config.app.config.user_id = "email" my_views = (("users", Register), ("access-tokens", LogInAndOut)) custom_claims = [NameClaim] Initialize( config.app, authenticate=authenticate, class_views=my_views, refresh_token_enabled=True, store_refresh_token=store_refresh_token, retrieve_refresh_token=retrieve_refresh_token, access_token_name="jwt", custom_claims=custom_claims, debug=True, path_to_retrieve_user="******", # little hacky user_id="email", expiration_delta=60 * 10, url_prefix="", authorization_header= "X-Access-Token", # FYI - this is not the standard implementation authorization_header_prefix="", retrieve_user=retrieve_user, path_to_refresh="/access-tokens/refresh", ) # # register Idea routes # config.app.add_route(update_idea, "/ideas/<id>", methods=["PUT"]) config.app.add_route(delete_idea, "/ideas/<id>", methods=["DELETE"]) config.app.add_route(create_idea, "/ideas", methods=["POST"]) config.app.add_route(get_ideas, "/ideas", methods=["GET"]) config.app.add_route(me_me_me, "/me", methods=["GET"])
def test_payload_not_a_dict(): app = Sanic() Initialize( app, authenticate=authenticate, authentication_class=AnotherWrongAuthentication, ) _, response = app.test_client.post( "/auth", json={"username": "******", "password": "******"} ) assert response.status == 500 assert response.json.get("exception") == "InvalidPayload"
def app_full_bytes_refresh_token(users, sanic_app, my_authentication_class, cache): class MyAuthentication(my_authentication_class): async def retrieve_refresh_token(self, user_id, *args, **kwargs): key = "refresh_token_{user_id}".format(user_id=user_id) token = cache.get(key, None).encode("utf-8") print(token, type(token)) return token sanicjwt = Initialize( sanic_app, authentication_class=MyAuthentication, refresh_token_enabled=True, ) yield (sanic_app, sanicjwt)
def app_with_user_secrets(username_table, authenticate, retrieve_user_secret): sanic_app = Sanic("sanic-jwt-test") sanic_jwt = Initialize( sanic_app, authenticate=authenticate, user_secret_enabled=True, retrieve_user_secret=retrieve_user_secret, ) @sanic_app.route("/protected") @protected() async def protected_request(request): return json({"protected": True}) yield (sanic_app, sanic_jwt)
def test_disable_protection(): app = Sanic("sanic-jwt-test") async def authenticate(request, *args, **kwargs): return {"user_id": 1} sanicjwt = Initialize(app, authenticate=authenticate, do_protection=False) @app.route("/protected") @sanicjwt.protected() def protected_route(request): return json({"protected": "yes"}) _, response = app.test_client.get("/protected") assert response.status == 200 assert response.json.get("protected") == "yes"
def test_custom_endpoints_as_args(): app = Sanic() sanicjwt = Initialize( app, authentication_class=MyAuthentication, refresh_token_enabled=True, auth_mode=False, class_views=custom_endpoints, ) @app.route("/protected") @sanicjwt.protected() async def protected_route(request): return json({"protected": "perhaps"}) _, response = app.test_client.post("/auth", json={"not": "important"}) assert response.status == 200 access_token = response.json.get(sanicjwt.config.access_token_name(), None) assert access_token is None assert response.json.get("hello") == msg.format("authentication") _, response = app.test_client.get("/auth/me") assert response.status == 200 assert response.json.get("hello") == msg.format("retrieve user") _, response = app.test_client.get("/auth/verify") assert response.status == 200 assert response.json.get("hello") == msg.format("verify") _, response = app.test_client.post( "/auth/refresh", json={"not": "important"} ) assert response.status == 200 assert response.json.get("hello") == msg.format("refresh") _, response = app.test_client.get("/protected") assert response.status == 401 assert response.json.get("exception") == "Unauthorized" assert "Authorization header not present." in response.json.get("reasons")
def app_with_retrieve_user(retrieve_user, authenticate): sanic_app = Sanic() sanic_jwt = Initialize( sanic_app, authenticate=authenticate, retrieve_user=retrieve_user ) @sanic_app.route("/") async def helloworld(request): return json({"hello": "world"}) @sanic_app.route("/protected") @protected() async def protected_request(request): return json({"protected": True}) yield (sanic_app, sanic_jwt)
def app_with_aud(username_table, authenticate): sanic_app = Sanic() sanic_jwt = Initialize( sanic_app, authenticate=authenticate, claim_aud="clientserver" ) @sanic_app.route("/") async def helloworld(request): return json({"hello": "world"}) @sanic_app.route("/protected") @protected() async def protected_request(request): return json({"protected": True}) yield (sanic_app, sanic_jwt)
def app_with_extended_exp(username_table, authenticate): sanic_app = Sanic() sanic_jwt = Initialize( sanic_app, authenticate=authenticate, expiration_delta=(60 * 60) ) @sanic_app.route("/") async def helloworld(request): return json({"hello": "world"}) @sanic_app.route("/protected") @protected() async def protected_request(request): return json({"protected": True}) yield (sanic_app, sanic_jwt)
def app_with_url_prefix(username_table, authenticate): sanic_app = Sanic() sanic_jwt = Initialize( sanic_app, authenticate=authenticate, url_prefix="/somethingelse" ) @sanic_app.route("/") async def helloworld(request): return json({"hello": "world"}) @sanic_app.route("/protected") @protected() async def protected_request(request): return json({"protected": True}) yield (sanic_app, sanic_jwt)
def app_with_leeway(username_table, authenticate): sanic_app = Sanic("sanic-jwt-test") sanic_jwt = Initialize(sanic_app, authenticate=authenticate, leeway=(60 * 5)) @sanic_app.route("/") async def helloworld(request): return json({"hello": "world"}) @sanic_app.route("/protected") @protected() async def protected_request(request): return json({"protected": True}) yield (sanic_app, sanic_jwt)