def get_authorization_request_for_access_token(self, access_token_value): # type: (str) -> oic.oic.message.AuthorizationRequest if access_token_value not in self.access_tokens: raise InvalidAccessToken('{} unknown'.format(access_token_value)) return AuthorizationRequest().from_dict( self.access_tokens[access_token_value][ self.KEY_AUTHORIZATION_REQUEST])
def test_registered_redirect_uri_with_query_component(): provider2 = Provider("FOOP", {}, {}, None, None, None, None, "") rr = RegistrationRequest(operation="register", redirect_uris=["http://example.org/cb?foo=bar"]) registration_req = rr.to_json() resp = provider2.registration_endpoint(request=registration_req) regresp = RegistrationResponse().from_json(resp.message) print regresp.to_dict() faulty = [ "http://example.org/cb", "http://example.org/cb/foo", "http://example.org/cb?got=you", "http://example.org/cb?foo=you" ] correct = [ "http://example.org/cb?foo=bar", "http://example.org/cb?foo=bar&got=you", "http://example.org/cb?foo=bar&foo=you" ] cid = regresp["client_id"] for ruri in faulty: areq = AuthorizationRequest(redirect_uri=ruri, client_id=cid, scope="openid", response_type="code") print areq try: provider2._verify_redirect_uri(areq) except RedirectURIError: pass for ruri in correct: areq = AuthorizationRequest(redirect_uri=ruri, client_id=cid, scope="openid", response_type="code") resp = provider2._verify_redirect_uri(areq) print resp assert resp is None
def create_refresh_token(self): sub = self.provider.authz_state.get_subject_identifier( 'pairwise', TEST_USER_ID, 'client1.example.com') auth_req = AuthorizationRequest().from_dict(self.authn_request_args) access_token = self.provider.authz_state.create_access_token( auth_req, sub) return self.provider.authz_state.create_refresh_token( access_token.value)
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
def test_registered_redirect_uri_without_query_component(): provider = Provider("FOO", {}, {}, None, None, None, None, "") rr = RegistrationRequest(operation="register", redirect_uris=["http://example.org/cb"]) registration_req = rr.to_json() provider.registration_endpoint(request=registration_req) correct = [ "http://example.org/cb", "http://example.org/cb/foo", "http://example.org/cb?got=you", "http://example.org/cb/foo?got=you" ] faulty = [ "http://example.org/foo", "http://example.com/cb", ] cid = _client_id(provider.cdb) for ruri in faulty: areq = AuthorizationRequest(redirect_uri=ruri, client_id=cid, response_type="code", scope="openid") print areq try: provider._verify_redirect_uri(areq) assert False except RedirectURIError: pass for ruri in correct: areq = AuthorizationRequest(redirect_uri=ruri, client_id=cid, response_type="code", scope="openid") print areq try: provider._verify_redirect_uri(areq) except RedirectURIError, err: print err assert False
def authn_req(self): state = "my_state" nonce = "nonce" redirect_uri = "https://client.example.com" claims_req = ClaimsRequest(id_token=Claims(email=None)) req = AuthorizationRequest(client_id=CLIENT_ID, state=state, scope="openid", response_type="id_token", redirect_uri=redirect_uri, nonce=nonce, claims=claims_req) return req
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 get_authorization_request_for_code(self, authorization_code): # type: (str) -> oic.oic.message.AuthorizationRequest if authorization_code not in self.authorization_codes: raise InvalidAuthorizationCode( '{} unknown'.format(authorization_code)) return AuthorizationRequest().from_dict( self.authorization_codes[authorization_code][ self.KEY_AUTHORIZATION_REQUEST])
def test_with_multiple_requested_sub(self): self.authn_request_args['claims'] = ClaimsRequest( userinfo=Claims(sub={'value': 'nomatch1'}), id_token=Claims(sub={'value': 'nomatch2'})) auth_req = AuthorizationRequest().from_dict(self.authn_request_args) with pytest.raises(AuthorizationError) as exc: self.provider.authorize(auth_req, TEST_USER_ID) assert 'different' in str(exc.value)
def test_verify_no_scopes(self): args = { "client_id": "foobar", "redirect_uri": "http://foobar.example.com/oaclient", "response_type": "code", } ar = AuthorizationRequest(**args) with pytest.raises(MissingRequiredAttribute): ar.verify()
def create_authz_code(self, extra_auth_req_params=None): sub = self.provider.authz_state.get_subject_identifier( 'pairwise', TEST_USER_ID, 'client1.example.com') if extra_auth_req_params: self.authn_request_args.update(extra_auth_req_params) auth_req = AuthorizationRequest().from_dict(self.authn_request_args) return self.provider.authz_state.create_authorization_code( auth_req, sub)
def test_default_transient_not_allowed(self): client_id = 'client1' provider = Mock() provider.clients = {client_id: {'allowed_scope_values': ['student']}} auth_req = AuthorizationRequest(scope='openid student', client_id=client_id) with pytest.raises(InvalidAuthenticationRequest): scope_is_valid_for_client(provider, auth_req)
def test_valid_claims_request_for_client(self): client_id = 'client1' provider = Mock() provider.clients = {client_id: {'allowed_claims': ['domain']}} auth_req = AuthorizationRequest( claims=ClaimsRequest(id_token=Claims(domain=None)), client_id=client_id) # should not raise an exception claims_request_is_valid_for_client(provider, auth_req)
def _get_authn_request_from_state(self, state): """ Extract the clietns request stoed in the SATOSA state. :type state: satosa.state.State :rtype: oic.oic.message.AuthorizationRequest :param state: the current state :return: the parsed authentication request """ return AuthorizationRequest().deserialize(state[self.name]["oidc_request"])
def test_claims_request_not_allowed_for_client(self): client_id = 'client1' provider = Mock() provider.clients = {client_id: {'allowed_claims': []}} auth_req = AuthorizationRequest( claims=ClaimsRequest(id_token=Claims(domain=None)), client_id=client_id) with pytest.raises(InvalidAuthenticationRequest): claims_request_is_valid_for_client(provider, auth_req)
def test_authorize_with_extra_id_token_claims(self, extra_claims): self.authn_request_args['response_type'] = [ 'id_token' ] # make sure ID Token is produced auth_req = AuthorizationRequest().from_dict(self.authn_request_args) resp = self.provider.authorize(auth_req, TEST_USER_ID, extra_claims) id_token = assert_id_token_base_claims(resp['id_token'], self.provider.signing_key, self.provider, auth_req) assert id_token['foo'] == 'bar'
def test_error_url_should_handle_unknown_response_type(self): authn_params = { 'redirect_uri': 'test_redirect_uri', 'state': 'test_state' } # no 'response_type' authn_req = AuthorizationRequest().from_dict(authn_params) error = InvalidAuthenticationRequest('test', authn_req, 'invalid_request') assert error.to_error_url() is None
def test_authorize_with_custom_sub(self, monkeypatch): sub = 'test_sub1' monkeypatch.setitem(self.provider.userinfo._db[TEST_USER_ID], 'sub', sub) auth_req = AuthorizationRequest().from_dict(self.authn_request_args) resp = self.provider.authorize(auth_req, TEST_USER_ID) assert resp['code'] in self.provider.authz_state.authorization_codes assert resp['state'] == self.authn_request_args['state'] assert self.provider.authz_state.authorization_codes[ resp['code']]['sub'] == sub
def test_valid_scope(self, scope, allowed_scope_values): client_id = 'client1' provider = Mock() provider.clients = { client_id: { 'allowed_scope_values': allowed_scope_values } } auth_req = AuthorizationRequest(scope=scope, client_id=client_id) # should not raise an exception scope_is_valid_for_client(provider, auth_req)
def test_idtoken(self): AREQ = AuthorizationRequest(response_type="code", client_id=CLIENT_ID, redirect_uri="http://example.com/authz", scope=["openid"], state="state000") ae = AuthnEvent("sub", "salt") sid = self.provider.sdb.create_authz_session(ae, AREQ) self.provider.sdb.do_sub(sid, "client_salt") session = self.provider.sdb[sid] id_token = self.provider.id_token_as_signed_jwt(session) assert len(id_token.split(".")) == 3
def test_error_url_should_contain_state_from_authentication_request(self): authn_params = { 'redirect_uri': 'test_redirect_uri', 'response_type': 'code', 'state': 'test_state' } authn_req = AuthorizationRequest().from_dict(authn_params) error_url = InvalidAuthenticationRequest( 'test', authn_req, 'invalid_request').to_error_url() error = dict(parse_qsl(urlparse(error_url).query)) assert error['state'] == authn_params['state']
def test_post_logout_redirect_with_unknown_post_logout_redirect_uri(self): auth_req = AuthorizationRequest( response_type='code id_token token', scope='openid', client_id='client1', redirect_uri='https://client.example.com/redirect') auth_resp = self.provider.authorize(auth_req, 'user1') end_session_request = EndSessionRequest( id_token_hint=auth_resp['id_token'], post_logout_redirect_uri='https://client.example.com/unknown') assert self.provider.do_post_logout_redirect( end_session_request) is None
def test_authz_request(): example = "https://server.example.com/authorize?response_type=token%20id_token&client_id=0acf77d4-b486-4c99-bd76-074ed6a64ddf&redirect_uri=https%3A%2F%2Fclient.example.com%2Fcb&scope=openid%20profile&state=af0ifjsldkj&nonce=n-0S6_WzA2Mj" req = AuthorizationRequest().deserialize(example.split("?")[1], "urlencoded") print req.keys() assert _eq(req.keys(), ['nonce', 'state', 'redirect_uri', 'response_type', 'client_id', 'scope']) assert req["response_type"] == ["token", "id_token"] assert req["scope"] == ["openid", "profile"]
def test_authorize_includes_requested_id_token_claims_even_if_token_request_can_be_made( self): self.authn_request_args['response_type'] = ['id_token', 'token'] self.authn_request_args['claims'] = ClaimsRequest(id_token=Claims( email=None)) auth_req = AuthorizationRequest().from_dict(self.authn_request_args) resp = self.provider.authorize(auth_req, TEST_USER_ID) id_token = assert_id_token_base_claims(resp['id_token'], self.provider.signing_key, self.provider, auth_req) assert id_token['email'] == self.provider.userinfo[TEST_USER_ID][ 'email']
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"
def test_get_approved_attributes(self, frontend): claims_req = ClaimsRequest(id_token=Claims(email=None), userinfo=Claims(userinfo_claim=None)) req = AuthorizationRequest(scope="openid profile", claims=claims_req) provider_supported_claims = [ "email", "name", "given_name", "family_name", "userinfo_claim", "extra_claim" ] result = frontend._get_approved_attributes(provider_supported_claims, req) assert Counter(result) == Counter( ["email", "name", "given_name", "family_name", "userinfo_claim"])
def test_idtoken(): server = provider_init AREQ = AuthorizationRequest(response_type="code", client_id=CLIENT_ID, redirect_uri="http://example.com/authz", scope=["openid"], state="state000") sid = server.sdb.create_authz_session("sub", AREQ) session = server.sdb[sid] id_token = server.id_token_as_signed_jwt(session) print id_token assert len(id_token.split(".")) == 3
def test_request_info_simple_get(self): uri, body, h_args, cis = self.client.request_info( AuthorizationRequest, method="GET", request_args={"scope": ["openid"], "response_type": "token"}) (url, query) = uri.split("?") areq = AuthorizationRequest().from_urlencoded(query) assert _eq(areq.keys(), ["nonce", "redirect_uri", "response_type", "client_id", "scope", "state"]) assert areq["redirect_uri"] == "http://client.example.com/authz" assert body is None assert h_args == {} assert cis.type() == "AuthorizationRequest"
def test_deserialize(self): query = "response_type=token%20id_token&client_id=0acf77d4-b486-4c99" \ "-bd76-074ed6a64ddf&redirect_uri=https%3A%2F%2Fclient.example" \ ".com%2Fcb&scope=openid%20profile&state=af0ifjsldkj&nonce=n" \ "-0S6_WzA2Mj" req = AuthorizationRequest().deserialize(query, "urlencoded") assert _eq(req.keys(), ['nonce', 'state', 'redirect_uri', 'response_type', 'client_id', 'scope']) assert req["response_type"] == ["token", "id_token"] assert req["scope"] == ["openid", "profile"]
def test_request_info_simple(self): self.client.authorization_endpoint = "https://example.com/authz" uri, body, h_args, cis = self.client.request_info( AuthorizationRequest, request_args={"scope": ["openid"], "response_type": "token"}) # default == "POST" assert uri == 'https://example.com/authz' areq = AuthorizationRequest().from_urlencoded(body) assert _eq(areq.keys(), ["nonce", "state", "redirect_uri", "response_type", "client_id", "scope"]) assert h_args == {'headers': { 'Content-type': 'application/x-www-form-urlencoded'}} assert cis.type() == "AuthorizationRequest"