Пример #1
0
def test_authz_req():
    areq = AuthorizationRequest(
        **{'state': 'vMTF1dV5yyEiPFR6',
           'redirect_uri': 'https://localhost:8088/authz_cb',
           'response_type': 'code', 'client_id': u'iSKYyH32tzC5',
           'scope': 'openid',
           'claims': {'id_token': {'sub': {"value": "-fdfb4a841dce167"}}}})

    print areq.to_urlencoded()
Пример #2
0
def test_server_authorization_endpoint_id_token():
    provider = provider_init

    bib = {
        "scope": ["openid"],
        "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
        "redirect_uri": "http://localhost:8087/authz",
        "response_type": ["code", "id_token"],
        "client_id": "a1b2c3",
        "nonce": "Nonce",
        "prompt": ["none"]
    }

    req = AuthorizationRequest(**bib)
    areq = AuthorizationRequest(response_type="code",
                                client_id="client_1",
                                redirect_uri="http://example.com/authz",
                                scope=["openid"],
                                state="state000")

    sdb = provider.sdb
    ae = AuthnEvent("userX")
    sid = sdb.create_authz_session(ae, areq)
    sdb.do_sub(sid)
    _info = sdb[sid]
    # All this is jut removed when the id_token is constructed
    # The proper information comes from the session information
    _user_info = IdToken(iss="https://foo.example.om",
                         sub="foo",
                         aud=bib["client_id"],
                         exp=epoch_in_a_while(minutes=10),
                         acr="2",
                         nonce=bib["nonce"])

    print provider.keyjar.issuer_keys
    print _user_info.to_dict()
    idt = provider.id_token_as_signed_jwt(_info,
                                          access_token="access_token",
                                          user_info=_user_info)

    req["id_token"] = idt
    query_string = req.to_urlencoded()

    # client_id not in id_token["aud"] so login required
    resp = provider.authorization_endpoint(request=query_string, cookie="FAIL")

    print resp
    assert "error=login_required" in resp.message

    req["client_id"] = "client_1"
    query_string = req.to_urlencoded()

    # client_id is in id_token["aud"] so no login required
    resp = provider.authorization_endpoint(request=query_string, cookie="FAIL")

    print resp.message
    assert resp.message.startswith("http://localhost:8087/authz")
Пример #3
0
    def test_authorization_endpoint_id_token(self):
        bib = {
            "scope": ["openid"],
            "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
            "redirect_uri": "http://localhost:8087/authz",
            "response_type": ["code", "id_token"],
            "client_id": "a1b2c3",
            "nonce": "Nonce",
            "prompt": ["none"],
        }

        req = AuthorizationRequest(**bib)
        areq = AuthorizationRequest(
            response_type="code",
            client_id="client_1",
            redirect_uri="http://example.com/authz",
            scope=["openid"],
            state="state000",
        )

        sdb = self.provider.sdb
        ae = AuthnEvent("userX", "salt")
        sid = sdb.create_authz_session(ae, areq)
        sdb.do_sub(sid, "client_salt")
        _info = sdb[sid]
        # All this is jut removed when the id_token is constructed
        # The proper information comes from the session information
        _user_info = IdToken(
            iss="https://foo.example.om",
            sub="foo",
            aud=bib["client_id"],
            exp=epoch_in_a_while(minutes=10),
            acr="2",
            nonce=bib["nonce"],
        )

        idt = self.provider.id_token_as_signed_jwt(_info, access_token="access_token", user_info=_user_info)

        req["id_token"] = idt
        query_string = req.to_urlencoded()

        # client_id not in id_token["aud"] so login required
        resp = self.provider.authorization_endpoint(request=query_string, cookie="FAIL")
        parsed_resp = parse_qs(urlparse(resp.message).fragment)
        assert parsed_resp["error"][0] == "login_required"

        req["client_id"] = "client_1"
        query_string = req.to_urlencoded()

        # client_id is in id_token["aud"] so no login required
        resp = self.provider.authorization_endpoint(request=query_string, cookie="FAIL")

        assert resp.message.startswith("http://localhost:8087/authz")
Пример #4
0
    def test_handle_authn_response_returns_id_token_for_verified_affiliation(
            self, signing_key_path, context, scope_value, affiliation):
        authn_req = AuthorizationRequest(
            scope='openid ' + scope_value,
            client_id='client1',
            redirect_uri='https://client.example.com',
            response_type='id_token')
        context.state[self.frontend.name] = {
            'oidc_request': authn_req.to_urlencoded()
        }
        internal_response = InternalResponse(
            AuthenticationInformation(None, str(datetime.now()),
                                      'https://idp.example.com'))
        internal_response.attributes['affiliation'] = [affiliation]
        internal_response.user_id = 'user1'

        resp = self.frontend.handle_authn_response(context, internal_response)
        auth_resp = AuthorizationResponse().from_urlencoded(
            urlparse(resp.message).fragment)

        id_token = IdToken().from_jwt(
            auth_resp['id_token'],
            key=[RSAKey(key=rsa_load(signing_key_path))])
        assert id_token['iss'] == self.frontend.base_url
        assert id_token['aud'] == ['client1']
        assert id_token['auth_time'] == internal_response.auth_info.timestamp
Пример #5
0
    def test_parse_authz_req(self):
        ar = AuthorizationRequest(
            response_type=["code"],
            client_id="foobar",
            redirect_uri="http://foobar.example.com/oaclient",
            state="cold",
            nonce="NONCE",
            scope=["openid"],
        )

        # query string
        uencq = ar.to_urlencoded()
        areq = self.srv.parse_authorization_request(query=uencq)

        assert isinstance(areq, AuthorizationRequest)
        assert areq["response_type"] == ["code"]
        assert areq["client_id"] == "foobar"
        assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
        assert areq["state"] == "cold"

        # urlencoded
        urluenc = "https://example.com/authz?{}".format(uencq)
        areq = self.srv.parse_authorization_request(url=urluenc)

        assert isinstance(areq, AuthorizationRequest)
        assert areq["response_type"] == ["code"]
        assert areq["client_id"] == "foobar"
        assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
        assert areq["state"] == "cold"
Пример #6
0
def test_server_authorization_endpoint_request():
    server = provider_init

    bib = {"scope": ["openid"],
           "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
           "redirect_uri": "http://localhost:8087/authz",
           "response_type": ["code", "id_token"],
           "client_id": "a1b2c3",
           "nonce": "Nonce",
           "prompt": ["none"]}

    req = AuthorizationRequest(**bib)
    ic = {"claims": {"sub": { "value":"username" }}}
    _keys = server.keyjar.get_signing_key(type="rsa")
    req["request"] = make_openid_request(req, _keys, idtoken_claims=ic,
                                         algorithm="RS256")

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

    resp = server.authorization_endpoint(environ, start_response)

    print resp
    line = resp[0]
    assert "error=login_required" in line
Пример #7
0
    def test_session_state_in_auth_req_for_session_support(self):
        provider = Provider(SERVER_INFO["issuer"],
                            SessionDB(SERVER_INFO["issuer"]),
                            CDB,
                            AUTHN_BROKER,
                            USERINFO,
                            AUTHZ,
                            verify_client,
                            SYMKEY,
                            urlmap=URLMAP,
                            keyjar=KEYJAR)

        provider.capabilities.update(
            {"check_session_iframe": "https://op.example.com/check_session"})

        req_args = {
            "scope": ["openid"],
            "redirect_uri": "http://localhost:8087/authz",
            "response_type": ["code"],
            "client_id": "number5"
        }
        areq = AuthorizationRequest(**req_args)
        resp = provider.authorization_endpoint(request=areq.to_urlencoded())
        aresp = self.cons.parse_response(AuthorizationResponse,
                                         resp.message,
                                         sformat="urlencoded")
        assert "session_state" in aresp
Пример #8
0
def test_server_parse_parse_authorization_request():
    srv = Server()
    srv.keyjar = KEYJ
    ar = AuthorizationRequest(response_type=["code"], client_id="foobar",
                              redirect_uri="http://foobar.example.com/oaclient",
                              state="cold", nonce="NONCE", scope=["openid"])

    uencq = ar.to_urlencoded()

    areq = srv.parse_authorization_request(query=uencq)

    assert areq.type() == "AuthorizationRequest"
    assert areq["response_type"] == ["code"]
    assert areq["client_id"] == "foobar"
    assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
    assert areq["state"] == "cold"

    urluenc = "%s?%s" % ("https://example.com/authz", uencq)

    areq = srv.parse_authorization_request(url=urluenc)

    assert areq.type() == "AuthorizationRequest"
    assert areq["response_type"] == ["code"]
    assert areq["client_id"] == "foobar"
    assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
    assert areq["state"] == "cold"
Пример #9
0
def test_server_parse_parse_authorization_request():
    srv = Server()
    srv.keyjar = KEYJ
    ar = AuthorizationRequest(
        response_type=["code"],
        client_id="foobar",
        redirect_uri="http://foobar.example.com/oaclient",
        state="cold",
        nonce="NONCE",
        scope=["openid"])

    uencq = ar.to_urlencoded()

    areq = srv.parse_authorization_request(query=uencq)

    assert areq.type() == "AuthorizationRequest"
    assert areq["response_type"] == ["code"]
    assert areq["client_id"] == "foobar"
    assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
    assert areq["state"] == "cold"

    urluenc = "%s?%s" % ("https://example.com/authz", uencq)

    areq = srv.parse_authorization_request(url=urluenc)

    assert areq.type() == "AuthorizationRequest"
    assert areq["response_type"] == ["code"]
    assert areq["client_id"] == "foobar"
    assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
    assert areq["state"] == "cold"
Пример #10
0
def test_server_authorization_endpoint_request():
    server = provider_init

    bib = {
        "scope": ["openid"],
        "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
        "redirect_uri": "http://localhost:8087/authz",
        "response_type": ["code", "id_token"],
        "client_id": "a1b2c3",
        "nonce": "Nonce",
        "prompt": ["none"]
    }

    req = AuthorizationRequest(**bib)
    # want to be someone else !
    ic = {"sub": {"value": "userX"}}
    _keys = server.keyjar.get_signing_key(key_type="RSA")
    req["request"] = make_openid_request(req,
                                         _keys,
                                         idtoken_claims=ic,
                                         algorithm="RS256")

    try:
        resp = server.authorization_endpoint(request=req.to_urlencoded())
    except FailedAuthentication:
        pass
    else:
        assert False
Пример #11
0
    def test_session_state_in_auth_req_for_session_support(self):
        provider = Provider(
            "foo",
            SessionDB(SERVER_INFO["issuer"]),
            CDB,
            AUTHN_BROKER,
            USERINFO,
            AUTHZ,
            verify_client,
            SYMKEY,
            urlmap=URLMAP,
            keyjar=KEYJAR,
            capabilities={"check_session_iframe": "https://op.example.com/check_session"},
        )

        req_args = {
            "scope": ["openid"],
            "redirect_uri": "http://localhost:8087/authz",
            "response_type": ["code"],
            "client_id": "a1b2c3",
        }
        areq = AuthorizationRequest(**req_args)
        resp = provider.authorization_endpoint(request=areq.to_urlencoded())
        aresp = self.cons.parse_response(AuthorizationResponse, resp.message, sformat="urlencoded")
        assert "session_state" in aresp
def test_scope_who_am_i(provider):
    registration_params = {
        "application_type": "web",
        "response_types": ["code", "token"],
        "redirect_uris": "http://example.org"
    }
    reg_req = RegistrationRequest(**registration_params)
    resp = provider.registration_endpoint(reg_req.to_urlencoded())
    reg_resp = RegistrationResponse().from_json(resp.message)

    auth_req = AuthorizationRequest(
        **{
            "client_id": reg_resp["client_id"],
            "scope": "openid who_am_i",
            "response_type": "code token",
            "redirect_uri": "http://example.org",
            "state": "state0",
            "nonce": "nonce0"
        })
    resp = provider.authorization_endpoint(auth_req.to_urlencoded())
    auth_resp = AuthorizationResponse().from_urlencoded(resp.message)

    userinfo_req = UserInfoRequest(
        **{"access_token": auth_resp["access_token"]})
    resp = provider.userinfo_endpoint(userinfo_req.to_urlencoded())
    userinfo_resp = AuthorizationResponse().from_json(resp.message)

    assert userinfo_resp["given_name"] == "Bruce"
    assert userinfo_resp["family_name"] == "Lee"
Пример #13
0
    def test_full_flow(self, context, frontend_with_extra_scopes):
        redirect_uri = "https://client.example.com/redirect"
        response_type = "code id_token token"
        mock_callback = Mock()
        frontend_with_extra_scopes.auth_req_callback_func = mock_callback
        # discovery
        http_response = frontend_with_extra_scopes.provider_config(context)
        provider_config = ProviderConfigurationResponse().deserialize(http_response.message, "json")

        # client registration
        registration_request = RegistrationRequest(redirect_uris=[redirect_uri], response_types=[response_type])
        context.request = registration_request.to_dict()
        http_response = frontend_with_extra_scopes.client_registration(context)
        registration_response = RegistrationResponse().deserialize(http_response.message, "json")

        # authentication request
        authn_req = AuthorizationRequest(
            redirect_uri=redirect_uri,
            client_id=registration_response["client_id"],
            response_type=response_type,
            scope="openid email eduperson",
            state="state",
            nonce="nonce",
        )
        context.request = dict(parse_qsl(authn_req.to_urlencoded()))
        frontend_with_extra_scopes.handle_authn_request(context)
        assert mock_callback.call_count == 1

        # fake authentication response from backend
        internal_response = self.setup_for_authn_response(
            context, frontend_with_extra_scopes, authn_req
        )
        http_response = frontend_with_extra_scopes.handle_authn_response(
            context, internal_response
        )
        authn_resp = AuthorizationResponse().deserialize(urlparse(http_response.message).fragment, "urlencoded")
        assert "code" in authn_resp
        assert "access_token" in authn_resp
        assert "id_token" in authn_resp

        # token request
        context.request = AccessTokenRequest(redirect_uri=authn_req["redirect_uri"], code=authn_resp["code"]).to_dict()
        credentials = "{}:{}".format(registration_response["client_id"], registration_response["client_secret"])
        basic_auth = urlsafe_b64encode(credentials.encode("utf-8")).decode("utf-8")
        context.request_authorization = "Basic {}".format(basic_auth)

        http_response = frontend_with_extra_scopes.token_endpoint(context)
        parsed = AccessTokenResponse().deserialize(http_response.message, "json")
        assert "access_token" in parsed
        assert "id_token" in parsed

        # userinfo request
        context.request = {}
        context.request_authorization = "Bearer {}".format(parsed["access_token"])
        http_response = frontend_with_extra_scopes.userinfo_endpoint(context)
        parsed = OpenIDSchema().deserialize(http_response.message, "json")
        assert "email" in parsed
        assert "eduperson_principal_name" in parsed
        assert "eduperson_scoped_affiliation" in parsed
Пример #14
0
def test_authz_req():
    areq = AuthorizationRequest(
        **{
            'state': 'vMTF1dV5yyEiPFR6',
            'redirect_uri': 'https://localhost:8088/authz_cb',
            'response_type': 'code',
            'client_id': u'iSKYyH32tzC5',
            'scope': 'openid',
            'claims': {
                'id_token': {
                    'sub': {
                        "value": "-fdfb4a841dce167"
                    }
                }
            }
        })

    print areq.to_urlencoded()
Пример #15
0
 def test_parse_authorization_request(self):
     areq = AuthorizationRequest(response_type="code", client_id="client_id",
                                 redirect_uri="http://example.com/authz",
                                 scope=["openid"], state="state0",
                                 nonce="N0nce")
     qdict = self.srv.parse_authorization_request(query=areq.to_urlencoded())
     assert _eq(qdict.keys(), ['nonce', 'state', 'redirect_uri',
                               'response_type', 'client_id', 'scope'])
     assert qdict["state"] == "state0"
 def test_parse_authorization_request(self):
     areq = AuthorizationRequest(response_type="code", client_id="client_id",
                                 redirect_uri="http://example.com/authz",
                                 scope=["openid"], state="state0",
                                 nonce="N0nce")
     qdict = self.srv.parse_authorization_request(query=areq.to_urlencoded())
     assert _eq(qdict.keys(), ['nonce', 'state', 'redirect_uri',
                               'response_type', 'client_id', 'scope'])
     assert qdict["state"] == "state0"
    def _authz_req(self):
        req_args = {"scope": ["openid", "profile"],
                    "redirect_uri": "http://localhost:8087/authz",
                    "response_type": ["code"],
                    "client_id": "client1"
                    }
        areq = AuthorizationRequest(**req_args)
        resp = self.provider.authorization_endpoint(areq.to_urlencoded())

        return AuthorizationResponse().deserialize(
            urlparse(resp.message).query, "urlencoded")
Пример #18
0
    def test_full_flow(self, context, frontend):
        redirect_uri = "https://client.example.com/redirect"
        response_type = "code id_token token"
        mock_callback = Mock()
        frontend.auth_req_callback_func = mock_callback
        # discovery
        http_response = frontend.provider_config(context)
        provider_config = ProviderConfigurationResponse().deserialize(http_response.message, "json")

        # client registration
        registration_request = RegistrationRequest(redirect_uris=[redirect_uri], response_types=[response_type])
        context.request = registration_request.to_dict()
        http_response = frontend.client_registration(context)
        registration_response = RegistrationResponse().deserialize(http_response.message, "json")

        # authentication request
        authn_req = AuthorizationRequest(
            redirect_uri=redirect_uri,
            client_id=registration_response["client_id"],
            response_type=response_type,
            scope="openid email",
            state="state",
            nonce="nonce",
        )
        context.request = dict(parse_qsl(authn_req.to_urlencoded()))
        frontend.handle_authn_request(context)
        assert mock_callback.call_count == 1

        # fake authentication response from backend
        internal_response = self.setup_for_authn_response(context, frontend, authn_req)
        http_response = frontend.handle_authn_response(context, internal_response)
        authn_resp = AuthorizationResponse().deserialize(urlparse(http_response.message).fragment, "urlencoded")
        assert "code" in authn_resp
        assert "access_token" in authn_resp
        assert "id_token" in authn_resp

        # token request
        context.request = AccessTokenRequest(redirect_uri=authn_req["redirect_uri"], code=authn_resp["code"]).to_dict()
        credentials = "{}:{}".format(registration_response["client_id"], registration_response["client_secret"])
        basic_auth = urlsafe_b64encode(credentials.encode("utf-8")).decode("utf-8")
        context.request_authorization = "Basic {}".format(basic_auth)

        http_response = frontend.token_endpoint(context)
        parsed = AccessTokenResponse().deserialize(http_response.message, "json")
        assert "access_token" in parsed
        assert "id_token" in parsed

        # userinfo request
        context.request = {}
        context.request_authorization = "Bearer {}".format(parsed["access_token"])
        http_response = frontend.userinfo_endpoint(context)
        parsed = OpenIDSchema().deserialize(http_response.message, "json")
        assert "email" in parsed
Пример #19
0
    def test_authorization_endpoint_bad_scope(self):
        bib = {"scope": ["openid", "offline_access"],
               "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
               "redirect_uri": "http://localhost:8087/authz",
               "response_type": ["code"],
               "client_id": "a1b2c3"}

        arq = AuthorizationRequest(**bib)
        resp = self.provider.authorization_endpoint(request=arq.to_urlencoded())
        assert resp.status == "303 See Other"
        parsed = parse_qs(urlparse(resp.message).query)
        assert parsed["error"][0] == "invalid_request"
        assert parsed["error_description"][0] == "consent in prompt"
Пример #20
0
    def test_handle_authn_response_returns_error_access_denied_for_wrong_affiliation(self, context, scope_value,
                                                                                     affiliation):
        authn_req = AuthorizationRequest(scope='openid ' + scope_value, client_id='client1',
                                         redirect_uri='https://client.example.com',
                                         response_type='id_token')
        context.state[self.frontend.name] = {'oidc_request': authn_req.to_urlencoded()}
        internal_response = InternalResponse()
        internal_response.attributes['affiliation'] = [affiliation]
        internal_response.user_id = 'user1'

        resp = self.frontend.handle_authn_response(context, internal_response)
        auth_resp = AuthorizationErrorResponse().from_urlencoded(urlparse(resp.message).fragment)
        assert auth_resp['error'] == 'access_denied'
Пример #21
0
    def test_server_authorization_endpoint(self):
        bib = {"scope": ["openid"],
               "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
               "redirect_uri": "http://localhost:8087/authz",
               "response_type": ["code"],
               "client_id": "a1b2c3",
               "nonce": "Nonce"}

        arq = AuthorizationRequest(**bib)

        resp = self.server.authorization_endpoint(request=arq.to_urlencoded())

        print resp.message
        assert resp.message
Пример #22
0
    def test_handle_backend_error(self, context, frontend):
        redirect_uri = "https://client.example.com"
        areq = AuthorizationRequest(client_id=CLIENT_ID, scope="openid", response_type="id_token",
                                    redirect_uri=redirect_uri)
        context.state[frontend.name] = {"oidc_request": areq.to_urlencoded()}

        # fake an error
        message = "test error"
        error = SATOSAAuthenticationError(context.state, message)
        resp = frontend.handle_backend_error(error)

        assert resp.message.startswith(redirect_uri)
        error_response = AuthorizationErrorResponse().deserialize(urlparse(resp.message).fragment)
        error_response["error"] = "access_denied"
        error_response["error_description"] == message
Пример #23
0
    def test_authorization_endpoint(self):
        bib = {"scope": ["openid"],
               "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
               "redirect_uri": "http://localhost:8087/authz",
               "response_type": ["code"],
               "client_id": "a1b2c3",
               "nonce": "Nonce"}

        arq = AuthorizationRequest(**bib)

        resp = self.provider.authorization_endpoint(request=arq.to_urlencoded())
        parsed = parse_qs(urlparse(resp.message).query)
        assert parsed["scope"] == ["openid"]
        assert parsed["state"][0] == "id-6da9ca0cc23959f5f33e8becd9b08cae"
        assert "code" in parsed
Пример #24
0
    def test_server_authorization_endpoint(self):
        bib = {
            "scope": ["openid"],
            "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
            "redirect_uri": "http://localhost:8087/authz",
            "response_type": ["code"],
            "client_id": "a1b2c3",
            "nonce": "Nonce"
        }

        arq = AuthorizationRequest(**bib)

        resp = self.server.authorization_endpoint(request=arq.to_urlencoded())

        print resp.message
        assert resp.message
Пример #25
0
def test_server_authorization_endpoint_id_token():
    provider = provider_init

    bib = {
        "scope": ["openid"],
        "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
        "redirect_uri": "http://localhost:8087/authz",
        "response_type": ["code", "id_token"],
        "client_id": "a1b2c3",
        "nonce": "Nonce",
        "prompt": ["none"]
    }

    req = AuthorizationRequest(**bib)
    AREQ = AuthorizationRequest(response_type="code",
                                client_id="client_1",
                                redirect_uri="http://example.com/authz",
                                scope=["openid"],
                                state="state000")

    sdb = SessionDB()
    sid = sdb.create_authz_session("userX", AREQ)

    _info = sdb[sid]
    _user_info = IdToken(iss="https://foo.example.om",
                         sub="foo",
                         aud=bib["client_id"],
                         exp=epoch_in_a_while(minutes=10),
                         acr="2",
                         nonce=bib["nonce"])

    print provider.keyjar.issuer_keys
    print _user_info.to_dict()
    idt = provider.id_token_as_signed_jwt(_info,
                                          access_token="access_token",
                                          user_info=_user_info)

    req["id_token"] = idt

    QUERY_STRING = req.to_urlencoded()

    resp = provider.authorization_endpoint(request=QUERY_STRING)

    print resp
    assert "error=login_required" in resp.message
Пример #26
0
    def test_handle_authn_response_returns_id_token_for_verified_affiliation(
            self, signing_key_path, context, scope_value, affiliation):
        authn_req = AuthorizationRequest(scope='openid ' + scope_value, client_id='client1',
                                         redirect_uri='https://client.example.com',
                                         response_type='id_token')
        context.state[self.frontend.name] = {'oidc_request': authn_req.to_urlencoded()}
        internal_response = InternalResponse(AuthenticationInformation(None, str(datetime.now()),
                                                                       'https://idp.example.com'))
        internal_response.attributes['affiliation'] = [affiliation]
        internal_response.user_id = 'user1'

        resp = self.frontend.handle_authn_response(context, internal_response)
        auth_resp = AuthorizationResponse().from_urlencoded(urlparse(resp.message).fragment)

        id_token = IdToken().from_jwt(auth_resp['id_token'], key=[RSAKey(key=rsa_load(signing_key_path))])
        assert id_token['iss'] == self.frontend.base_url
        assert id_token['aud'] == ['client1']
        assert id_token['auth_time'] == internal_response.auth_info.timestamp
Пример #27
0
    def test_authorization_endpoint_request(self):
        bib = {"scope": ["openid"],
               "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
               "redirect_uri": "http://localhost:8087/authz",
               "response_type": ["code", "id_token"],
               "client_id": "a1b2c3",
               "nonce": "Nonce",
               "prompt": ["none"]}

        req = AuthorizationRequest(**bib)
        # want to be someone else !
        ic = {"sub": {"value": "userX"}}
        _keys = self.provider.keyjar.get_signing_key(key_type="RSA")
        req["request"] = make_openid_request(req, _keys, idtoken_claims=ic,
                                             request_object_signing_alg="RS256")

        with pytest.raises(FailedAuthentication):
            self.provider.authorization_endpoint(request=req.to_urlencoded())
Пример #28
0
    def test_handle_authn_response_returns_error_access_denied_for_wrong_affiliation(
            self, context, scope_value, affiliation):
        authn_req = AuthorizationRequest(
            scope='openid ' + scope_value,
            client_id='client1',
            redirect_uri='https://client.example.com',
            response_type='id_token')
        context.state[self.frontend.name] = {
            'oidc_request': authn_req.to_urlencoded()
        }
        internal_response = InternalResponse()
        internal_response.attributes['affiliation'] = [affiliation]
        internal_response.user_id = 'user1'

        resp = self.frontend.handle_authn_response(context, internal_response)
        auth_resp = AuthorizationErrorResponse().from_urlencoded(
            urlparse(resp.message).fragment)
        assert auth_resp['error'] == 'access_denied'
Пример #29
0
def test_server_authorization_endpoint():
    server = provider_init

    bib = {"scope": ["openid"],
           "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
           "redirect_uri": "http://localhost:8087/authz",
           "response_type": ["code"],
           "client_id": "a1b2c3",
           "nonce": "Nonce"}

    arq = AuthorizationRequest(**bib)

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

    resp = server.authorization_endpoint(environ, start_response)

    print resp
    line = resp[0]
    assert line.startswith("<form>")
    assert line.endswith("</form>")
Пример #30
0
def test_server_authorization_endpoint_id_token():
    provider = provider_init

    bib = {"scope": ["openid"],
           "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
           "redirect_uri": "http://localhost:8087/authz",
           "response_type": ["code", "id_token"],
           "client_id": "a1b2c3",
           "nonce": "Nonce",
           "prompt": ["none"]}

    req = AuthorizationRequest(**bib)
    AREQ = AuthorizationRequest(response_type="code",
                                client_id="client_1",
                                redirect_uri="http://example.com/authz",
                                scope=["openid"], state="state000")

    sdb = SessionDB()
    sid = sdb.create_authz_session("username", AREQ)

    _info = sdb[sid]
    _user_info = IdToken(iss="https://foo.example.om", sub="foo",
                         aud=bib["client_id"], exp=epoch_in_a_while(minutes=10),
                        acr="2", nonce=bib["nonce"])

    print provider.keyjar.issuer_keys
    print _user_info.to_dict()
    idt = provider.id_token_as_signed_jwt(_info, access_token="access_token",
                                          user_info=_user_info)

    req["id_token"] = idt

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

    resp = provider.authorization_endpoint(environ, start_response)

    print resp
    line = resp[0]
    assert "error=login_required" in line
Пример #31
0
def test_server_authorization_endpoint_request():
    server = provider_init

    bib = {"scope": ["openid"],
           "state": "id-6da9ca0cc23959f5f33e8becd9b08cae",
           "redirect_uri": "http://localhost:8087/authz",
           "response_type": ["code", "id_token"],
           "client_id": "a1b2c3",
           "nonce": "Nonce",
           "prompt": ["none"]}

    req = AuthorizationRequest(**bib)
    # want to be someone else !
    ic = {"sub": {"value": "userX"}}
    _keys = server.keyjar.get_signing_key(key_type="RSA")
    req["request"] = make_openid_request(req, _keys, idtoken_claims=ic,
                                         algorithm="RS256")

    resp = server.authorization_endpoint(request=req.to_urlencoded())

    print resp
    assert "error=login_required" in resp.message
def test_scope_who_am_i(provider):
    registration_params = {
        "application_type": "web",
        "response_types": ["code", "token"],
        "redirect_uris": "http://example.org"}
    reg_req = RegistrationRequest(**registration_params)
    resp = provider.registration_endpoint(reg_req.to_urlencoded())
    reg_resp = RegistrationResponse().from_json(resp.message)

    auth_req = AuthorizationRequest(
        **{"client_id": reg_resp["client_id"], "scope": "openid who_am_i",
           "response_type": "code token",
           "redirect_uri": "http://example.org", "state": "state0", "nonce": "nonce0"})
    resp = provider.authorization_endpoint(auth_req.to_urlencoded())
    auth_resp = AuthorizationResponse().from_urlencoded(resp.message)

    userinfo_req = UserInfoRequest(**{"access_token": auth_resp["access_token"]})
    resp = provider.userinfo_endpoint(userinfo_req.to_urlencoded())
    userinfo_resp = AuthorizationResponse().from_json(resp.message)

    assert userinfo_resp["given_name"] == "Bruce"
    assert userinfo_resp["family_name"] == "Lee"
    def test_parse_authz_req(self):
        ar = AuthorizationRequest(response_type=["code"], client_id="foobar",
                                  redirect_uri="http://foobar.example.com/oaclient",
                                  state="cold", nonce="NONCE", scope=["openid"])

        # query string
        uencq = ar.to_urlencoded()
        areq = self.srv.parse_authorization_request(query=uencq)

        assert isinstance(areq, AuthorizationRequest)
        assert areq["response_type"] == ["code"]
        assert areq["client_id"] == "foobar"
        assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
        assert areq["state"] == "cold"

        # urlencoded
        urluenc = "https://example.com/authz?{}".format(uencq)
        areq = self.srv.parse_authorization_request(url=urluenc)

        assert isinstance(areq, AuthorizationRequest)
        assert areq["response_type"] == ["code"]
        assert areq["client_id"] == "foobar"
        assert areq["redirect_uri"] == "http://foobar.example.com/oaclient"
        assert areq["state"] == "cold"