def test_authenticated_requirement_succeeds_with_identity(): requirement = AuthenticatedRequirement() context = AuthorizationContext(User({}, 'oidc'), [requirement]) requirement.handle(context) assert context.has_succeeded
async def test_static_files_allow_anonymous_by_default(): app = FakeApplication() app.use_authentication().add(MockNotAuthHandler()) app.use_authorization().add( AdminsPolicy()).default_policy += AuthenticatedRequirement() @app.router.get("/") async def home(): return None app.serve_files(get_folder_path("files")) await app.start() await app(get_example_scope("GET", "/"), MockReceive(), MockSend()) assert app.response.status == 401 await app(get_example_scope("GET", "/lorem-ipsum.txt"), MockReceive(), MockSend()) assert app.response.status == 200 content = await app.response.text() assert content == "Lorem ipsum dolor sit amet\n"
async def test_static_files_support_authentication(): app = FakeApplication() app.use_authentication().add(MockNotAuthHandler()) app.use_authorization().add( AdminsPolicy()).default_policy += AuthenticatedRequirement() @app.router.get("/") async def home(): return None app.serve_files( ServeFilesOptions(get_folder_path("files"), allow_anonymous=False)) await app.start() await app(get_example_scope("GET", "/"), MockReceive(), MockSend()) assert app.response.status == 401 await app(get_example_scope("GET", "/lorem-ipsum.txt"), MockReceive(), MockSend()) assert app.response.status == 401
def use_authorization( self, strategy: Optional[AuthorizationStrategy] = None ) -> AuthorizationStrategy: if self.started: raise RuntimeError( "The application is already running, configure authorization " "before starting the application" ) if not strategy: strategy = AuthorizationStrategy() if strategy.default_policy is None: # by default, a default policy is configured with no requirements, # meaning that request handlers allow anonymous users by default, unless # they are decorated with @auth() strategy.default_policy = Policy("default") strategy.add(Policy("authenticated").add(AuthenticatedRequirement())) self._authorization_strategy = strategy self.exceptions_handlers[ AuthenticateChallenge ] = handle_authentication_challenge self.exceptions_handlers[UnauthorizedError] = handle_unauthorized return strategy
def test_policy_add_method(): strategy = AuthorizationStrategy(default_policy=Policy('default')) auth_req = AuthenticatedRequirement() strategy.default_policy.add(auth_req) assert strategy.default_policy.requirements[0] is auth_req
def test_policy_iadd_syntax(): strategy = AuthorizationStrategy(default_policy=Policy('default')) auth_req = AuthenticatedRequirement() strategy.default_policy += auth_req assert strategy.default_policy.requirements[0] is auth_req
async def test_auth_using_default_policy_failing(): auth: AuthorizationStrategy = get_strategy([]) auth.default_policy = Policy('authenticated', AuthenticatedRequirement()) @auth() async def some_method(): return True with raises(UnauthorizedError): await some_method()
async def test_static_files_support_authentication_by_route(): app = FakeApplication() app.use_authentication().add(MockNotAuthHandler()) app.use_authorization().add( AdminsPolicy()).default_policy += AuthenticatedRequirement() @app.router.get("/") async def home(): return None app.serve_files( ServeFilesOptions(get_folder_path("files"), allow_anonymous=False)) app.serve_files( ServeFilesOptions(get_folder_path("files2"), allow_anonymous=True, root_path="/login")) await app.start() await app(get_example_scope("GET", "/"), MockReceive(), MockSend()) assert app.response.status == 401 await app(get_example_scope("GET", "/lorem-ipsum.txt"), MockReceive(), MockSend()) assert app.response.status == 401 await app(get_example_scope("GET", "/login/index.html"), MockReceive(), MockSend()) assert app.response.status == 200 content = await app.response.text() assert (content == """<!DOCTYPE html> <html> <head> <title>Example.</title> <link rel="stylesheet" type="text/css" href="/styles/main.css" /> </head> <body> <h1>Lorem ipsum</h1> <p>Dolor sit amet.</p> <script src="/scripts/main.js"></script> </body> </html> """)
async def test_authorization_supports_default_require_authenticated(): app = FakeApplication() app.use_authentication().add(MockNotAuthHandler()) app.use_authorization().add( AdminsPolicy()).default_policy += AuthenticatedRequirement() @app.router.get("/") async def home(): return None app.prepare() await app(get_example_scope("GET", "/"), MockReceive(), MockSend()) assert app.response.status == 401
async def test_authorization_supports_allow_anonymous(app, mock_receive, mock_send): from blacksheep.server.responses import text app.use_authentication().add(MockNotAuthHandler()) app.use_authorization().add( AdminsPolicy() ).default_policy += AuthenticatedRequirement() @allow_anonymous() @app.router.get("/") async def home(): return text("Hi There!") app.prepare() await app(get_example_scope("GET", "/"), mock_receive(), mock_send) assert app.response.status == 200
async def test_authentication_challenge_response(): app = FakeApplication() app.use_authentication().add(AccessTokenCrashingHandler()) app.use_authorization().add( AdminsPolicy()).default_policy += AuthenticatedRequirement() @app.router.get("/") async def home(): return None app.prepare() await app(get_example_scope("GET", "/"), MockReceive(), MockSend()) assert app.response.status == 401 header = app.response.get_single_header(b"WWW-Authenticate") assert header is not None assert header == (b'Bearer, error="Invalid access token", ' b'error_description="Access token expired"')
pass async def authenticate(self, context): header_value = context.get_first_header(b"Authorization") if header_value: data = json.loads(urlsafe_b64decode(header_value).decode("utf8")) context.identity = Identity(data, "FAKE") else: context.identity = None return context.identity app_two.use_authentication().add(MockAuthHandler()) app_two.use_authorization().add(AdminsPolicy()).add( Policy("authenticated", AuthenticatedRequirement())) @auth("admin") @app_two.router.get("/only-for-admins") async def only_for_admins(): return None @auth("authenticated") @app_two.router.get("/only-for-authenticated-users") async def only_for_authenticated_users(): return None @app_two.route("/crash")
async def authenticate(self, context): header_value = context.get_first_header(b'Authorization') if header_value: data = json.loads(urlsafe_b64decode(header_value).decode('utf8')) context.identity = Identity(data, 'FAKE') else: context.identity = None return context.identity app_two.use_authentication().add(MockAuthHandler()) app_two.use_authorization()\ .add(AdminsPolicy())\ .add(Policy('authenticated', AuthenticatedRequirement())) @auth('admin') @app_two.router.get('/only-for-admins') async def only_for_admins(): return None @auth('authenticated') @app_two.router.get('/only-for-authenticated-users') async def only_for_authenticated_users(): return None @app_two.route('/crash')