Example #1
0
def _validate_authorization(app_config: AppConfig, context: EventContext,
                            auth_types: List[AuthType], request: web.Request):
    """
    Validates Authorization header from request to provide valid credentials
    for the methods supported in event configuration.

    :raise `Unauthorized` if authorization is not valid
    """
    auth_methods = context.event_info.auth
    if (len(auth_methods) == 0) and (app_config.server is not None):
        auth_methods = app_config.server.auth.default_auth_methods
    auth_header = _extract_authorization(auth_methods, request, context)

    try:
        method, data = auth_header.split(" ")
    except ValueError as e:
        raise BadRequest("Malformed Authorization") from e

    context.auth_info['allowed'] = False
    for auth_type in auth_types:
        if method.upper() == auth_type.name.upper():
            auth.validate_auth_method(auth_type, data, context)
            if context.auth_info.get('allowed'):
                return None
    raise Unauthorized(method)
Example #2
0
def test_auth_method_unsecured(mock_app_config):  # noqa: F811
    context = _setup_server_context(mock_app_config)
    assert auth.validate_auth_method(
        AuthType.UNSECURED,
        data='',
        context=context) is None
    assert context.auth_info['allowed']
    assert context.auth_info['auth_type'] == AuthType.UNSECURED
Example #3
0
def test_auth_method_basic(mock_app_config):  # noqa: F811
    context = _setup_server_context(mock_app_config)
    assert auth.validate_auth_method(
        AuthType.BASIC,
        data='dGVzdDpwYXNz',
        context=context) is None
    assert context.auth_info['allowed']
    assert context.auth_info['auth_type'] == AuthType.BASIC
    assert context.auth_info['payload'] == 'dGVzdDpwYXNz'
Example #4
0
def test_auth_method_refresh(mock_app_config):  # noqa: F811
    context = _setup_event_context(mock_app_config)
    payload = {'test': 'test_value', 'exp': datetime.now().astimezone(timezone.utc) + timedelta(seconds=2)}
    token = auth.new_token(payload)
    assert auth.validate_auth_method(
        AuthType.REFRESH,
        data=token,
        context=context) is None
    assert context.auth_info['allowed']
    assert context.auth_info['auth_type'] == AuthType.REFRESH
    assert context.auth_info['payload'] == auth.decode_token(token)
Example #5
0
def test_auth_method_bearer(mock_app_config):  # noqa: F811
    context = _setup_server_context(mock_app_config)
    payload = {
        'test': 'test_value',
        'exp': datetime.now(tz=timezone.utc) + timedelta(seconds=2)
    }
    token = auth.new_token(mock_app_config.app_key(), payload)
    assert auth.validate_auth_method(
        AuthType.BEARER,
        data=token,
        context=context) is None
    assert context.auth_info['allowed']
    assert context.auth_info['auth_type'] == AuthType.BEARER
    assert context.auth_info['payload'] == auth.decode_token(token)