Exemple #1
0
    def test_authenticated(self):
        _session_db = {}
        cons = Consumer(_session_db, client_config=CLIENT_CONFIG,
                        server_info=SERVER_INFO, **CONSUMER_CONFIG)

        sid, location = cons.begin("http://localhost:8087",
                                   "http://localhost:8088/authorization")

        resp = self.provider.authorization_endpoint(urlparse(location).query)
        assert resp.status == "303 See Other"
        resp = urlparse(resp.message).query
        with LogCapture(level=logging.DEBUG) as logcap:
            aresp = cons.handle_authorization_response(query=resp)

        assert isinstance(aresp, AuthorizationResponse)
        assert _eq(aresp.keys(), ['state', 'code', 'client_id', 'iss'])
        assert _eq(cons.grant[sid].keys(), ['tokens', 'code', 'exp_in',
                                            'seed', 'id_token',
                                            'grant_expiration_time'])

        state = aresp['state']
        assert _eq(logcap.records[0].msg, '- authorization - code flow -')
        assert logcap.records[1].msg in expected_outcome(
            'QUERY: ', ['state={}'.format(state), 'code=<REDACTED>',
                        'client_id=client1',
                        'iss=https%3A%2F%2Fexample.com%2Fas'])
        expected = {'iss': 'https://example.com/as',
                    'state': state, 'code': '<REDACTED>',
                    'client_id': 'client1'}
        # Eval here to avoid intermittent failures due to dict ordering
        assert _eq(eval(logcap.records[2].msg[29:-1]), expected)
        expected = ["'client_id': 'client1'", "'iss': 'https://example.com/as'",
                    "'keyjar': <KeyJar(issuers=[])>"]
        assert _eq(sorted(logcap.records[3].msg[22:-1].split(', ')), expected)
def test_consumer_parse_access_token():
    # implicit flow test
    _session_db = {}
    cons = Consumer(_session_db, client_config=CLIENT_CONFIG,
                    server_info=SERVER_INFO, **CONSUMER_CONFIG)
    cons.debug = True
    environ = BASE_ENVIRON

    cons.response_type = ["token"]
    sid, loc = cons.begin("http://localhost:8087",
                          "http://localhost:8088/authorization")

    atr = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA",
                              token_type="example",
                              refresh_token="tGzv3JOkF0XG5Qx2TlKWIA",
                              example_parameter="example_value",
                              state=sid)

    res = cons.handle_authorization_response(query=atr.to_urlencoded())

    assert res.type() == "AccessTokenResponse"
    print cons.grant[sid]
    grant = cons.grant[sid]
    assert len(grant.tokens) == 1
    token = grant.tokens[0]
    assert token.access_token == "2YotnFZFEjr1zCsicMWpAA"
def test_consumer_parse_access_token():
    # implicit flow test
    _session_db = {}
    cons = Consumer(_session_db,
                    client_config=CLIENT_CONFIG,
                    server_info=SERVER_INFO,
                    **CONSUMER_CONFIG)
    cons.debug = True
    environ = BASE_ENVIRON

    cons.response_type = ["token"]
    _ = cons.begin("http://localhost:8087",
                   "http://localhost:8088/authorization")

    atr = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA",
                              token_type="example",
                              refresh_token="tGzv3JOkF0XG5Qx2TlKWIA",
                              example_parameter="example_value",
                              state=cons.state)

    res = cons.handle_authorization_response(query=atr.to_urlencoded())

    assert res.type() == "AccessTokenResponse"
    print cons.grant[cons.state]
    grant = cons.grant[cons.state]
    assert len(grant.tokens) == 1
    token = grant.tokens[0]
    assert token.access_token == "2YotnFZFEjr1zCsicMWpAA"
def test_consumer_parse_access_token():
    # implicit flow test
    _session_db = {}
    cons = Consumer(_session_db, client_config = CLIENT_CONFIG,
                    server_info=SERVER_INFO, **CONSUMER_CONFIG)
    cons.debug = True
    environ = BASE_ENVIRON

    cons.response_type = ["token"]
    _ = cons.begin(environ, start_response)

    atr = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA",
                              token_type="example",
                              refresh_token="tGzv3JOkF0XG5Qx2TlKWIA",
                              example_parameter="example_value",
                              state=cons.state)

    environ = BASE_ENVIRON.copy()
    environ["QUERY_STRING"] = atr.to_urlencoded()

    res = cons.handle_authorization_response(environ, start_response)

    assert res.type() ==  "AccessTokenResponse"
    print cons.grant[cons.state]
    grant = cons.grant[cons.state]
    assert len(grant.tokens) == 1
    token = grant.tokens[0]
    assert token.access_token == "2YotnFZFEjr1zCsicMWpAA"
def test_provider_authenticated():
    provider = Provider("pyoicserv", sdb.SessionDB(), CDB, AUTHN_BROKER, AUTHZ,
                        verify_client, symkey=rndstr(16))
    _session_db = {}
    cons = Consumer(_session_db, client_config=CLIENT_CONFIG,
                    server_info=SERVER_INFO, **CONSUMER_CONFIG)
    cons.debug = True

    location = cons.begin("http://localhost:8087",
                          "http://localhost:8088/authorization")

    query_string = location.split("?")[1]

    resp = provider.authorization_endpoint(query_string)
    assert resp.status == "302 Found"
    print resp.headers
    print resp.message
    if content_type(resp.headers) == "json":
        resp = resp.message
    else:
        resp = resp.message.split("?")[1]
    aresp = cons.handle_authorization_response(query=resp)

    print aresp.keys()
    assert aresp.type() == "AuthorizationResponse"
    assert _eq(aresp.keys(), ['state', 'code'])

    print cons.grant[cons.state].keys()
    assert _eq(cons.grant[cons.state].keys(), ['tokens', 'code', 'exp_in',
                                               'seed', 'id_token',
                                               'grant_expiration_time'])
Exemple #6
0
    def test_authenticated(self):
        _session_db = DictSessionBackend()
        cons = Consumer(
            _session_db,
            client_config=CLIENT_CONFIG,
            server_info=SERVER_INFO,
            **CONSUMER_CONFIG,
        )

        sid, location = cons.begin("http://localhost:8087",
                                   "http://localhost:8088/authorization")

        resp = self.provider.authorization_endpoint(urlparse(location).query)
        assert resp.status_code == 303
        resp = urlparse(resp.message).query
        with LogCapture(level=logging.DEBUG) as logcap:
            aresp = cons.handle_authorization_response(query=resp)

        assert isinstance(aresp, AuthorizationResponse)
        assert _eq(aresp.keys(), ["state", "code", "client_id", "iss"])
        assert _eq(
            cons.grant[sid].keys(),
            [
                "tokens", "code", "exp_in", "seed", "id_token",
                "grant_expiration_time"
            ],
        )

        state = aresp["state"]
        assert _eq(logcap.records[0].msg, "- authorization - code flow -")
        assert verify_outcome(
            logcap.records[1].msg,
            "QUERY: ",
            [
                "state={}".format(state),
                "code=<REDACTED>",
                "client_id=client1",
                "iss=https://example.com/as",
            ],
        )

        expected = {
            "iss": "https://example.com/as",
            "state": state,
            "code": "<REDACTED>",
            "client_id": "client1",
        }
        # Eval here to avoid intermittent failures due to dict ordering
        assert _eq(eval(logcap.records[2].msg[29:-1]), expected)
        expected2 = [
            "'client_id': 'client1'",
            "'iss': 'https://example.com/as'",
            "'keyjar': <KeyJar(issuers=[])>",
        ]
        assert _eq(sorted(logcap.records[3].msg[22:-1].split(", ")), expected2)
    def test_authenticated(self):
        _session_db = {}
        cons = Consumer(_session_db, client_config=CLIENT_CONFIG, server_info=SERVER_INFO, **CONSUMER_CONFIG)

        sid, location = cons.begin("http://localhost:8087", "http://localhost:8088/authorization")

        resp = self.provider.authorization_endpoint(urlparse(location).query)
        assert resp.status == "302 Found"
        resp = urlparse(resp.message).query
        aresp = cons.handle_authorization_response(query=resp)

        assert isinstance(aresp, AuthorizationResponse)
        assert _eq(aresp.keys(), ["state", "code"])
        assert _eq(cons.grant[sid].keys(), ["tokens", "code", "exp_in", "seed", "id_token", "grant_expiration_time"])
def test_provider_authenticated():
    provider = Provider("pyoicserv", sdb.SessionDB(), CDB, FUNCTIONS)
    _session_db = {}
    cons = Consumer(_session_db, client_config = CLIENT_CONFIG,
                    server_info=SERVER_INFO, **CONSUMER_CONFIG)
    cons.debug = True
    environ = BASE_ENVIRON

    location = cons.begin(environ, start_response)

    environ = BASE_ENVIRON.copy()
    environ["QUERY_STRING"] = location.split("?")[1]

    resp = provider.authorization_endpoint(environ, start_response)

    sid = resp[0][len("FORM with "):]
    environ2 = create_return_form_env("user", "password", sid)

    resp2 = provider.authenticated(environ2, start_response)

    print resp2[0]
    assert len(resp2) == 1
    txt = resp2[0]
    pos0 = txt.index("<title>") + len("<title>Redirecting to ")
    pos1 = txt.index("</title>")
    location = txt[pos0:pos1]
    print location

    assert location.startswith("http://localhost:8087/authz")

    environ = BASE_ENVIRON.copy()
    environ["QUERY_STRING"] = location.split("?")[1]

    aresp = cons.handle_authorization_response(environ, start_response)

    #aresp = client.parse_response(AuthorizationResponse, location,
    #                              format="urlencoded",
    #                              state="id-6da9ca0cc23959f5f33e8becd9b08cae")

    print aresp.keys()
    assert aresp.type() == "AuthorizationResponse"
    assert _eq(aresp.keys(), ['state', 'code'])

    print cons.grant[cons.state].keys()
    assert _eq(cons.grant[cons.state].keys(), ['tokens', 'code', 'exp_in',
                                               'seed', 'id_token',
                                               'grant_expiration_time'])
def test_consumer_handle_authorization_response():
    _session_db = {}
    cons = Consumer(_session_db, client_config=CLIENT_CONFIG,
                    server_info=SERVER_INFO, **CONSUMER_CONFIG)
    cons.debug = True

    sid, loc = cons.begin("http://localhost:8087",
                          "http://localhost:8088/authorization")

    atr = AuthorizationResponse(code="SplxlOBeZQQYbYS6WxSbIA",
                                state=sid)

    res = cons.handle_authorization_response(query=atr.to_urlencoded())

    assert res.type() == "AuthorizationResponse"
    print cons.grant[sid]
    grant = cons.grant[sid]
    assert grant.code == "SplxlOBeZQQYbYS6WxSbIA"
Exemple #10
0
    def test_authenticated(self):
        _session_db = {}
        cons = Consumer(_session_db,
                        client_config=CLIENT_CONFIG,
                        server_info=SERVER_INFO,
                        **CONSUMER_CONFIG)

        sid, location = cons.begin("http://localhost:8087",
                                   "http://localhost:8088/authorization")

        resp = self.provider.authorization_endpoint(urlparse(location).query)
        assert resp.status_code == 303
        resp = urlparse(resp.message).query
        with LogCapture(level=logging.DEBUG) as logcap:
            aresp = cons.handle_authorization_response(query=resp)

        assert isinstance(aresp, AuthorizationResponse)
        assert _eq(aresp.keys(), ['state', 'code', 'client_id', 'iss'])
        assert _eq(cons.grant[sid].keys(), [
            'tokens', 'code', 'exp_in', 'seed', 'id_token',
            'grant_expiration_time'
        ])

        state = aresp['state']
        assert _eq(logcap.records[0].msg, '- authorization - code flow -')
        assert verify_outcome(logcap.records[1].msg, 'QUERY: ', [
            'state={}'.format(state), 'code=<REDACTED>', 'client_id=client1',
            'iss=https://example.com/as'
        ])

        expected = {
            'iss': 'https://example.com/as',
            'state': state,
            'code': '<REDACTED>',
            'client_id': 'client1'
        }
        # Eval here to avoid intermittent failures due to dict ordering
        assert _eq(eval(logcap.records[2].msg[29:-1]), expected)
        expected = [
            "'client_id': 'client1'", "'iss': 'https://example.com/as'",
            "'keyjar': <KeyJar(issuers=[])>"
        ]
        assert _eq(sorted(logcap.records[3].msg[22:-1].split(', ')), expected)
def test_consumer_handle_authorization_response():
    _session_db = {}
    cons = Consumer(_session_db,
                    client_config=CLIENT_CONFIG,
                    server_info=SERVER_INFO,
                    **CONSUMER_CONFIG)
    cons.debug = True

    sid, loc = cons.begin("http://localhost:8087",
                          "http://localhost:8088/authorization")

    atr = AuthorizationResponse(code="SplxlOBeZQQYbYS6WxSbIA", state=sid)

    res = cons.handle_authorization_response(query=atr.to_urlencoded())

    assert res.type() == "AuthorizationResponse"
    print cons.grant[sid]
    grant = cons.grant[sid]
    assert grant.code == "SplxlOBeZQQYbYS6WxSbIA"
def test_consumer_handle_authorization_response():
    _session_db = {}
    cons = Consumer(_session_db, client_config = CLIENT_CONFIG,
                    server_info=SERVER_INFO, **CONSUMER_CONFIG)
    cons.debug = True
    environ = BASE_ENVIRON

    _ = cons.begin(environ, start_response)

    atr = AuthorizationResponse(code="SplxlOBeZQQYbYS6WxSbIA",
                                state=cons.state)

    environ = BASE_ENVIRON.copy()
    environ["QUERY_STRING"] = atr.to_urlencoded()

    res = cons.handle_authorization_response(environ, start_response)

    assert res.type() == "AuthorizationResponse"
    print cons.grant[cons.state]
    grant = cons.grant[cons.state]
    assert grant.code == "SplxlOBeZQQYbYS6WxSbIA"
Exemple #13
0
    def test_authenticated(self):
        _session_db = {}
        cons = Consumer(_session_db,
                        client_config=CLIENT_CONFIG,
                        server_info=SERVER_INFO,
                        **CONSUMER_CONFIG)

        sid, location = cons.begin("http://localhost:8087",
                                   "http://localhost:8088/authorization")

        resp = self.provider.authorization_endpoint(urlparse(location).query)
        assert resp.status == "302 Found"
        resp = urlparse(resp.message).query
        aresp = cons.handle_authorization_response(query=resp)

        assert isinstance(aresp, AuthorizationResponse)
        assert _eq(aresp.keys(), ['state', 'code'])
        assert _eq(cons.grant[sid].keys(), [
            'tokens', 'code', 'exp_in', 'seed', 'id_token',
            'grant_expiration_time'
        ])
Exemple #14
0
def test_provider_authenticated():
    provider = Provider("pyoicserv",
                        sdb.SessionDB(),
                        CDB,
                        AUTHN_BROKER,
                        AUTHZ,
                        verify_client,
                        symkey=rndstr(16))
    _session_db = {}
    cons = Consumer(_session_db,
                    client_config=CLIENT_CONFIG,
                    server_info=SERVER_INFO,
                    **CONSUMER_CONFIG)
    cons.debug = True

    location = cons.begin("http://localhost:8087",
                          "http://localhost:8088/authorization")

    query_string = location.split("?")[1]

    resp = provider.authorization_endpoint(query_string)
    assert resp.status == "302 Found"
    print resp.headers
    print resp.message
    if content_type(resp.headers) == "json":
        resp = resp.message
    else:
        resp = resp.message.split("?")[1]
    aresp = cons.handle_authorization_response(query=resp)

    print aresp.keys()
    assert aresp.type() == "AuthorizationResponse"
    assert _eq(aresp.keys(), ['state', 'code'])

    print cons.grant[cons.state].keys()
    assert _eq(cons.grant[cons.state].keys(), [
        'tokens', 'code', 'exp_in', 'seed', 'id_token', 'grant_expiration_time'
    ])
Exemple #15
0
class TestConsumer(object):
    @pytest.fixture(autouse=True)
    def create_consumer(self):
        self.consumer = Consumer(
            DictSessionBackend(),
            client_config=CLIENT_CONFIG,
            server_info=SERVER_INFO,
            settings=CLIENT_SETTINGS,
            **CONSUMER_CONFIG,
        )

    def test_init(self):
        cons = Consumer(
            DictSessionBackend(),
            client_config=CLIENT_CONFIG,
            server_info=SERVER_INFO,
            settings=CLIENT_SETTINGS,
            **CONSUMER_CONFIG,
        )
        cons._backup("123456")
        assert "123456" in cons.sdb

        cons = Consumer(
            DictSessionBackend(),
            client_config=CLIENT_CONFIG,
            settings=CLIENT_SETTINGS,
            **CONSUMER_CONFIG,
        )
        assert cons.authorization_endpoint is None

        cons = Consumer(DictSessionBackend, **CONSUMER_CONFIG)
        assert cons.authorization_endpoint is None

    def test_begin(self):
        sid, loc = self.consumer.begin("http://localhost:8087",
                                       "http://localhost:8088/authorization")

        # state is dynamic
        params = {
            "scope": "openid",
            "state": sid,
            "redirect_uri": "http://localhost:8087/authz",
            "response_type": "code",
            "client_id": "number5",
        }

        url = "http://localhost:8088/authorization?{}".format(
            urlencode(params))
        assert url_compare(loc, url)

    def test_handle_authorization_response(self):
        sid, loc = self.consumer.begin("http://localhost:8087",
                                       "http://localhost:8088/authorization")

        atr = AuthorizationResponse(code="SplxlOBeZQQYbYS6WxSbIA", state=sid)

        res = self.consumer.handle_authorization_response(
            query=atr.to_urlencoded())

        assert isinstance(res, AuthorizationResponse)
        assert self.consumer.grant[sid].code == "SplxlOBeZQQYbYS6WxSbIA"

    def test_parse_authz_without_code(self):
        sid, loc = self.consumer.begin("http://localhost:8087",
                                       "http://localhost:8088/authorization")

        atr = AuthorizationResponse(code="SplxlOBeZQQYbYS6WxSbIA", state=sid)

        adict = atr.to_dict()
        del adict["code"]

        with pytest.raises(MissingRequiredAttribute):
            self.consumer.handle_authorization_response(query=urlencode(adict))

    def test_parse_authz_access_denied(self):
        sid, loc = self.consumer.begin("http://localhost:8087",
                                       "http://localhost:8088/authorization")

        atr = AuthorizationErrorResponse(error="access_denied", state=sid)

        with pytest.raises(AuthzError):
            self.consumer.handle_authorization_response(
                query=atr.to_urlencoded())

    def test_parse_access_token(self):
        # implicit flow test
        self.consumer.response_type = ["token"]
        sid, loc = self.consumer.begin("http://localhost:8087",
                                       "http://localhost:8088/authorization")

        atr = AccessTokenResponse(
            access_token="2YotnFZFEjr1zCsicMWpAA",
            token_type="example",
            refresh_token="tGzv3JOkF0XG5Qx2TlKWIA",
            example_parameter="example_value",
            state=sid,
        )

        res = self.consumer.handle_authorization_response(
            query=atr.to_urlencoded())

        assert isinstance(res, AccessTokenResponse)
        grant = self.consumer.grant[sid]
        assert len(grant.tokens) == 1
        token = grant.tokens[0]
        assert token.access_token == "2YotnFZFEjr1zCsicMWpAA"

    def test_parse_authz_invalid_client(self):
        self.consumer.begin("http://localhost:8087",
                            "http://localhost:8088/authorization")

        atr = TokenErrorResponse(error="invalid_client")

        with pytest.raises(AuthzError):
            self.consumer.handle_authorization_response(
                query=atr.to_urlencoded())

    def test_consumer_client_auth_info(self):
        self.consumer.client_secret = "secret0"
        ra, ha, extra = self.consumer.client_auth_info()
        assert ra == {"client_secret": "secret0", "client_id": "number5"}
        assert ha == {}
        assert extra == {"auth_method": "bearer_body"}

    def test_provider_config(self):
        c = Consumer(None, None)
        response = ASConfigurationResponse(
            **{
                "issuer": "https://example.com",
                "end_session_endpoint": "https://example.com/end_session",
            })
        with responses.RequestsMock() as rsps:
            rsps.add(
                responses.GET,
                "https://example.com/.well-known/openid-configuration",
                json=response.to_dict(),
            )
            info = c.provider_config("https://example.com")
        assert isinstance(info, ASConfigurationResponse)
        assert _eq(info.keys(), ["issuer", "version", "end_session_endpoint"])
        assert info[
            "end_session_endpoint"] == "https://example.com/end_session"

    def test_client_get_access_token_request(self):
        self.consumer.client_secret = "secret0"
        _state = "state"
        self.consumer.redirect_uris = ["https://www.example.com/oic/cb"]

        resp1 = AuthorizationResponse(code="auth_grant", state=_state)
        self.consumer.parse_response(AuthorizationResponse,
                                     resp1.to_urlencoded(), "urlencoded")
        resp2 = AccessTokenResponse(access_token="token1",
                                    token_type="Bearer",
                                    expires_in=0,
                                    state=_state)
        self.consumer.parse_response(AccessTokenResponse,
                                     resp2.to_urlencoded(), "urlencoded")

        url, body, http_args = self.consumer.get_access_token_request(_state)
        assert url_compare(url, "http://localhost:8088/token")
        expected_params = (
            "redirect_uri=https%3A%2F%2Fwww.example.com%2Foic%2Fcb&client_id=number5&state=state&"
            "code=auth_grant&grant_type=authorization_code&client_secret=secret0"
        )

        assert query_string_compare(body, expected_params)
        assert http_args == {
            "headers": {
                "Content-Type": "application/x-www-form-urlencoded"
            }
        }

    def test_access_token_storage_with_custom_response_class(self):
        _state = "state"

        # AccessTokenResponse custom class
        class AccessTokenResponseWrapper(AccessTokenResponse):
            """Response wrapper to get "expires_in" in hours."""

            c_param = AccessTokenResponse.c_param.copy()
            c_param.update({"expires_in_hours": SINGLE_OPTIONAL_INT})

            def __init__(self, **kwargs):
                super(AccessTokenResponseWrapper, self).__init__(**kwargs)
                if "expires_in" in self and self["expires_in"]:
                    self["expires_in_hours"] = self["expires_in"] // 3600

        resp = AccessTokenResponseWrapper(
            access_token="2YotnFZFEjr1zCsiAB",
            token_type="Bearer",
            expires_in=3600,
            state=_state,
        )
        self.consumer.parse_response(AccessTokenResponseWrapper,
                                     resp.to_urlencoded(), "urlencoded")

        grant = self.consumer.grant[_state]
        assert len(grant.tokens) == 1
        assert grant.tokens[0].access_token == "2YotnFZFEjr1zCsiAB"
        assert grant.tokens[
            0].token_expiration_time > time_util.time_sans_frac()
        assert grant.tokens[0].expires_in_hours == 1  # type: ignore
Exemple #16
0
class TestConsumer(object):
    @pytest.fixture(autouse=True)
    def create_consumer(self):
        self.consumer = Consumer({},
                                 client_config=CLIENT_CONFIG,
                                 server_info=SERVER_INFO,
                                 **CONSUMER_CONFIG)

    def test_init(self):
        cons = Consumer({},
                        client_config=CLIENT_CONFIG,
                        server_info=SERVER_INFO,
                        **CONSUMER_CONFIG)
        cons._backup("123456")
        assert "123456" in cons.sdb

        cons = Consumer({}, client_config=CLIENT_CONFIG, **CONSUMER_CONFIG)
        assert cons.authorization_endpoint is None

        cons = Consumer({}, **CONSUMER_CONFIG)
        assert cons.authorization_endpoint is None

    def test_begin(self):
        sid, loc = self.consumer.begin("http://localhost:8087",
                                       "http://localhost:8088/authorization")

        # state is dynamic
        params = {
            "scope": "openid",
            "state": sid,
            "redirect_uri": "http://localhost:8087/authz",
            "response_type": "code",
            "client_id": "number5"
        }

        url = "http://localhost:8088/authorization?{}".format(
            urlencode(params))
        assert url_compare(loc, url)

    def test_handle_authorization_response(self):
        sid, loc = self.consumer.begin("http://localhost:8087",
                                       "http://localhost:8088/authorization")

        atr = AuthorizationResponse(code="SplxlOBeZQQYbYS6WxSbIA", state=sid)

        res = self.consumer.handle_authorization_response(
            query=atr.to_urlencoded())

        assert isinstance(res, AuthorizationResponse)
        assert self.consumer.grant[sid].code == "SplxlOBeZQQYbYS6WxSbIA"

    def test_parse_authz_without_code(self):
        sid, loc = self.consumer.begin("http://localhost:8087",
                                       "http://localhost:8088/authorization")

        atr = AuthorizationResponse(code="SplxlOBeZQQYbYS6WxSbIA", state=sid)

        adict = atr.to_dict()
        del adict["code"]

        with pytest.raises(MissingRequiredAttribute):
            self.consumer.handle_authorization_response(query=urlencode(adict))

    def test_parse_authz_access_denied(self):
        sid, loc = self.consumer.begin("http://localhost:8087",
                                       "http://localhost:8088/authorization")

        atr = AuthorizationErrorResponse(error="access_denied", state=sid)

        with pytest.raises(AuthzError):
            self.consumer.handle_authorization_response(
                query=atr.to_urlencoded())

    def test_parse_access_token(self):
        # implicit flow test
        self.consumer.response_type = ["token"]
        sid, loc = self.consumer.begin("http://localhost:8087",
                                       "http://localhost:8088/authorization")

        atr = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA",
                                  token_type="example",
                                  refresh_token="tGzv3JOkF0XG5Qx2TlKWIA",
                                  example_parameter="example_value",
                                  state=sid)

        res = self.consumer.handle_authorization_response(
            query=atr.to_urlencoded())

        assert isinstance(res, AccessTokenResponse)
        grant = self.consumer.grant[sid]
        assert len(grant.tokens) == 1
        token = grant.tokens[0]
        assert token.access_token == "2YotnFZFEjr1zCsicMWpAA"

    def test_parse_authz_invalid_client(self):
        self.consumer.begin("http://localhost:8087",
                            "http://localhost:8088/authorization")

        atr = TokenErrorResponse(error="invalid_client")

        with pytest.raises(AuthzError):
            self.consumer.handle_authorization_response(
                query=atr.to_urlencoded())

    def test_consumer_client_auth_info(self):
        self.consumer.client_secret = "secret0"
        ra, ha, extra = self.consumer.client_auth_info()
        assert ra == {'client_secret': 'secret0', 'client_id': 'number5'}
        assert ha == {}
        assert extra == {'auth_method': 'bearer_body'}

    def test_client_get_access_token_request(self):
        self.consumer.client_secret = "secret0"
        _state = "state"
        self.consumer.redirect_uris = ["https://www.example.com/oic/cb"]

        resp1 = AuthorizationResponse(code="auth_grant", state=_state)
        self.consumer.parse_response(AuthorizationResponse,
                                     resp1.to_urlencoded(), "urlencoded")
        resp2 = AccessTokenResponse(access_token="token1",
                                    token_type="Bearer",
                                    expires_in=0,
                                    state=_state)
        self.consumer.parse_response(AccessTokenResponse,
                                     resp2.to_urlencoded(), "urlencoded")

        url, body, http_args = self.consumer.get_access_token_request(_state)
        assert url_compare(url, "http://localhost:8088/token")
        expected_params = 'redirect_uri=https%3A%2F%2Fwww.example.com%2Foic%2Fcb&client_id=number5&state=state&' \
                          'code=auth_grant&grant_type=authorization_code&client_secret=secret0'

        assert query_string_compare(body, expected_params)
        assert http_args == {
            'headers': {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }
Exemple #17
0
fields = list(form.fields.items())
#print fields
form["login"] = "******"
form['password'] = '******'
#form.set('name', 'Bob', index=0)

res = form.submit(extra_environ={"oic.server":SERVER, "mako.lookup":LOOKUP})
assert res.status == "302 Found"
url = res.headers["location"]

# Parse by the client

environ = BASE_ENVIRON.copy()
environ["QUERY_STRING"] = url
_cli = Consumer(SESSION_DB, CLIENT_CONFIG, SERVER_INFO, **CONSUMER_CONFIG)
aresp = _cli.handle_authorization_response(environ, start_response, DEVNULL())

print "ARESP: %s" % aresp

assert isinstance(aresp, AuthorizationResponse)

# Create the AccessTokenRequest
url, body, http_args = _cli.get_access_token_request(environ, start_response,
                                                     DEVNULL())

assert url == "http://localhost:8088/token"
assert len(body) != 0
assert http_args == {"client_password": "******"}

# complete with access token request
class TestConsumer(object):
    @pytest.fixture(autouse=True)
    def create_consumer(self):
        self.consumer = Consumer({}, client_config=CLIENT_CONFIG,
                                 server_info=SERVER_INFO,
                                 **CONSUMER_CONFIG)

    def test_init(self):
        cons = Consumer({}, client_config=CLIENT_CONFIG,
                        server_info=SERVER_INFO,
                        **CONSUMER_CONFIG)
        cons._backup("123456")
        assert "123456" in cons.sdb

        cons = Consumer({}, client_config=CLIENT_CONFIG, **CONSUMER_CONFIG)
        assert cons.authorization_endpoint is None

        cons = Consumer({}, **CONSUMER_CONFIG)
        assert cons.authorization_endpoint is None

    def test_begin(self):
        sid, loc = self.consumer.begin("http://localhost:8087",
                                       "http://localhost:8088/authorization")

        # state is dynamic
        params = {"scope": "openid",
                  "state": sid,
                  "redirect_uri": "http://localhost:8087/authz",
                  "response_type": "code",
                  "client_id": "number5"}

        url = "http://localhost:8088/authorization?{}".format(urlencode(params))
        assert url_compare(loc, url)

    def test_handle_authorization_response(self):
        sid, loc = self.consumer.begin("http://localhost:8087",
                                       "http://localhost:8088/authorization")

        atr = AuthorizationResponse(code="SplxlOBeZQQYbYS6WxSbIA",
                                    state=sid)

        res = self.consumer.handle_authorization_response(
            query=atr.to_urlencoded())

        assert isinstance(res, AuthorizationResponse)
        assert self.consumer.grant[sid].code == "SplxlOBeZQQYbYS6WxSbIA"

    def test_parse_authz_without_code(self):
        sid, loc = self.consumer.begin("http://localhost:8087",
                                       "http://localhost:8088/authorization")

        atr = AuthorizationResponse(code="SplxlOBeZQQYbYS6WxSbIA",
                                    state=sid)

        adict = atr.to_dict()
        del adict["code"]

        with pytest.raises(MissingRequiredAttribute):
            self.consumer.handle_authorization_response(query=urlencode(adict))

    def test_parse_authz_access_denied(self):
        sid, loc = self.consumer.begin("http://localhost:8087",
                                       "http://localhost:8088/authorization")

        atr = AuthorizationErrorResponse(error="access_denied", state=sid)

        with pytest.raises(AuthzError):
            self.consumer.handle_authorization_response(
                query=atr.to_urlencoded())

    def test_parse_access_token(self):
        # implicit flow test
        self.consumer.response_type = ["token"]
        sid, loc = self.consumer.begin("http://localhost:8087",
                                       "http://localhost:8088/authorization")

        atr = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA",
                                  token_type="example",
                                  refresh_token="tGzv3JOkF0XG5Qx2TlKWIA",
                                  example_parameter="example_value",
                                  state=sid)

        res = self.consumer.handle_authorization_response(
            query=atr.to_urlencoded())

        assert isinstance(res, AccessTokenResponse)
        grant = self.consumer.grant[sid]
        assert len(grant.tokens) == 1
        token = grant.tokens[0]
        assert token.access_token == "2YotnFZFEjr1zCsicMWpAA"

    def test_parse_authz_invalid_client(self):
        self.consumer.begin("http://localhost:8087",
                            "http://localhost:8088/authorization")

        atr = TokenErrorResponse(error="invalid_client")

        with pytest.raises(AuthzError):
            self.consumer.handle_authorization_response(
                query=atr.to_urlencoded())

    def test_consumer_client_auth_info(self):
        self.consumer.client_secret = "secret0"
        ra, ha, extra = self.consumer.client_auth_info()
        assert ra == {'client_secret': 'secret0', 'client_id': 'number5'}
        assert ha == {}
        assert extra == {'auth_method': 'bearer_body'}

    def test_client_get_access_token_request(self):
        self.consumer.client_secret = "secret0"
        _state = "state"
        self.consumer.redirect_uris = ["https://www.example.com/oic/cb"]

        resp1 = AuthorizationResponse(code="auth_grant", state=_state)
        self.consumer.parse_response(AuthorizationResponse,
                                     resp1.to_urlencoded(),
                                     "urlencoded")
        resp2 = AccessTokenResponse(access_token="token1",
                                    token_type="Bearer", expires_in=0,
                                    state=_state)
        self.consumer.parse_response(AccessTokenResponse, resp2.to_urlencoded(),
                                     "urlencoded")

        url, body, http_args = self.consumer.get_access_token_request(_state)
        assert url_compare(url, "http://localhost:8088/token")
        expected_params = 'code=auth_grant&redirect_uri=https%3A%2F%2Fwww' \
                          '.example.com%2Foic%2Fcb&client_id=number5' \
                          '&client_secret=secret0&grant_type=authorization_code&state_hash=S6aXNcpTdl7WpwnttWxuoja3GTo7KaazkMNG8PQ0Dk4%3D'

        assert query_string_compare(body, expected_params)
        assert http_args == {'headers': {
            'Content-Type': 'application/x-www-form-urlencoded'}}