def test_consumer_client_get_access_token_reques(): _session_db = {} cons = Consumer(_session_db, client_config=CLIENT_CONFIG, server_info=SERVER_INFO, **CONSUMER_CONFIG) cons.client_secret = "secret0" _state = "state" cons.redirect_uris = ["https://www.example.com/oic/cb"] resp1 = AuthorizationResponse(code="auth_grant", state=_state) cons.parse_response(AuthorizationResponse, resp1.to_urlencoded(), "urlencoded") resp2 = AccessTokenResponse(access_token="token1", token_type="Bearer", expires_in=0, state=_state) cons.parse_response(AccessTokenResponse, resp2.to_urlencoded(), "urlencoded") url, body, http_args = cons.get_access_token_request(_state) assert url == "http://localhost:8088/token" print body assert body == ("code=auth_grant&client_secret=secret0&" "grant_type=authorization_code&client_id=number5&" "redirect_uri=https%3A%2F%2Fwww.example.com%2Foic%2Fcb") assert http_args == {'headers': { 'Content-type': 'application/x-www-form-urlencoded'}}
def test_consumer_client_get_access_token_reques(): _session_db = {} cons = Consumer(_session_db, client_config=CLIENT_CONFIG, server_info=SERVER_INFO, **CONSUMER_CONFIG) cons.client_secret = "secret0" cons.state = "state" cons.redirect_uris = ["https://www.example.com/oic/cb"] resp1 = AuthorizationResponse(code="auth_grant", state="state") cons.parse_response(AuthorizationResponse, resp1.to_urlencoded(), "urlencoded") resp2 = AccessTokenResponse(access_token="token1", token_type="Bearer", expires_in=0, state="state") cons.parse_response(AccessTokenResponse, resp2.to_urlencoded(), "urlencoded") url, body, http_args = cons.get_access_token_request() assert url == "http://localhost:8088/token" print body assert body == ("code=auth_grant&client_secret=secret0&" "grant_type=authorization_code&client_id=number5&" "redirect_uri=https%3A%2F%2Fwww.example.com%2Foic%2Fcb") assert http_args == { 'headers': { 'Content-type': 'application/x-www-form-urlencoded' } }
def test_consumer_client_get_access_token_reques(): _session_db = {} cons = Consumer(_session_db, client_config=CLIENT_CONFIG, server_info=SERVER_INFO, **CONSUMER_CONFIG) cons.client_secret = "secret0" _state = "state" cons.redirect_uris = ["https://www.example.com/oic/cb"] resp1 = AuthorizationResponse(code="auth_grant", state=_state) cons.parse_response(AuthorizationResponse, resp1.to_urlencoded(), "urlencoded") resp2 = AccessTokenResponse(access_token="token1", token_type="Bearer", expires_in=0, state=_state) cons.parse_response(AccessTokenResponse, resp2.to_urlencoded(), "urlencoded") url, body, http_args = cons.get_access_token_request(_state) url_obj = URLObject.create(url) expected_url_obj = URLObject.create("http://localhost:8088/token") assert url_obj == expected_url_obj body_splits = body.split('&') expected_body_splits = "code=auth_grant&client_secret=secret0&" \ "grant_type=authorization_code&client_id=number5&" \ "redirect_uri=https%3A%2F%2Fwww.example.com%2Foic%2Fcb".split('&') assert set(body_splits) == set(expected_body_splits) assert http_args == { 'headers': { 'Content-type': 'application/x-www-form-urlencoded' } }
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_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_construct_with_token(self, client): resp1 = AuthorizationResponse(code="auth_grant", state="state") client.parse_response(AuthorizationResponse, resp1.to_urlencoded(), "urlencoded") resp2 = AccessTokenResponse(access_token="token1", token_type="Bearer", expires_in=0, state="state") client.parse_response(AccessTokenResponse, resp2.to_urlencoded(), "urlencoded") http_args = BearerHeader(client).construct(ResourceRequest(), state="state") assert http_args == {"headers": {"Authorization": "Bearer token1"}}
def test_construct_with_request(self, client): resp1 = AuthorizationResponse(code="auth_grant", state="state") client.parse_response(AuthorizationResponse, resp1.to_urlencoded(), "urlencoded") resp2 = AccessTokenResponse(access_token="token1", token_type="Bearer", expires_in=0, state="state") client.parse_response(AccessTokenResponse, resp2.to_urlencoded(), "urlencoded") cis = ResourceRequest() BearerBody(client).construct(cis, state="state") assert "access_token" in cis assert cis["access_token"] == "token1"
def test_init(self): atr = AuthorizationResponse(code="SplxlOBeZQQYbYS6WxSbIA", state="Fun_state", extra="foo") assert atr["code"] == "SplxlOBeZQQYbYS6WxSbIA" assert atr["state"] == "Fun_state" assert atr["extra"] == "foo"
def test_get_grant(self): resp = AuthorizationResponse(code="code", state="state") grant = Grant() grant.add_code(resp) self.client.grant["state"] = grant assert self.client.grant_from_state("state").code == "code"
def code_response(**kwargs): _areq = kwargs["areq"] _scode = kwargs["scode"] aresp = AuthorizationResponse() if "state" in _areq: aresp["state"] = _areq["state"] aresp["code"] = _scode add_non_standard(_areq, aresp) return aresp
def test_construct_access_token_req_expired_grant(self): resp = AuthorizationResponse(code="code", state="state") grant = Grant(-10) # expired grant grant.add_code(resp) client = Client() client.grant["openid"] = grant with pytest.raises(GrantExpired): client.construct_AccessTokenRequest(state="openid")
def test_consumer_parse_authz_exception(): _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) adict = atr.to_dict() del adict["code"] QUERY_STRING = urllib.urlencode(adict) raises(MissingRequiredAttribute, "cons.handle_authorization_response(query=QUERY_STRING)")
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_parse_authz_exception(): _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) adict = atr.to_dict() del adict["code"] environ = BASE_ENVIRON.copy() environ["QUERY_STRING"] = urllib.urlencode(adict) raises(MissingRequiredAttribute, "cons.handle_authorization_response(environ, start_response)")
def code_response(**kwargs): _areq = kwargs["areq"] _scode = kwargs["scode"] aresp = AuthorizationResponse() try: aresp["state"] = _areq["state"] except KeyError: pass aresp["code"] = _scode add_non_standard(_areq, aresp) return aresp
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"
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 code_response(**kwargs): aresp = AuthorizationResponse() _areq = kwargs["areq"] try: aresp["state"] = _areq["state"] except KeyError: pass aresp["code"] = kwargs["scode"] # TODO Add 'iss' and 'client_id' if kwargs['myself']: aresp['iss'] = kwargs['myself'] aresp['client_id'] = _areq['client_id'] add_non_standard(_areq, aresp) return aresp
def test_grant_access_token(): resp = AuthorizationResponse(code="code", state="state") grant = Grant() grant.add_code(resp) atr = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA", token_type="example", refresh_token="tGzv3JOkF0XG5Qx2TlKWIA", example_parameter="example_value", scope=["inner", "outer"]) grant.add_token(atr) assert len(grant.tokens) == 1 token = grant.tokens[0] assert token.is_valid() is True assert str(grant) != ""
def test_construct_with_state(self, client): resp = AuthorizationResponse(code="code", state="state") grant = Grant() grant.add_code(resp) atr = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA", token_type="example", refresh_token="tGzv3JOkF0XG5Qx2TlKWIA", example_parameter="example_value", scope=["inner", "outer"]) grant.add_token(atr) client.grant["state"] = grant cis = ResourceRequest() http_args = BearerBody(client).construct(cis, {}, state="state", scope="inner") assert cis["access_token"] == "2YotnFZFEjr1zCsicMWpAA" assert http_args is None
def authz_part2(self, user, areq, skey, permission=None, authn=None, **kwargs): """ After the authentication this is where you should end up :param user: :param areq: The Authorization Request :param skey: Session key :param permission: A permission specification :param authn: The Authentication Method used :param kwargs: possible other parameters :return: A redirect to the redirect_uri of the client """ _log_debug = logger.debug _log_debug("- in authenticated() -") self.sdb.update(skey, "auz", permission) _log_debug("response type: %s" % areq["response_type"]) # create the response aresp = AuthorizationResponse() try: aresp["state"] = areq["state"] except KeyError: pass if "response_type" in areq and \ len(areq["response_type"]) == 1 and \ "none" in areq["response_type"]: pass else: # if self.sdb.is_revoked(sinfo): # return self._error(error="access_denied", # descr="Token is revoked") try: aresp["scope"] = areq["scope"] except KeyError: pass _log_debug("_dic: %s" % self.sdb[skey]) rtype = set(areq["response_type"][:]) if "code" in areq["response_type"]: #if issue_new_code: # scode = self.sdb.duplicate(_sinfo) # _sinfo = self.sdb[scode] _code = aresp["code"] = self.sdb.get_token(skey) rtype.remove("code") else: _code = self.sdb[skey]["code"] self.sdb.update(skey, "code", None) if "token" in rtype: self.sdb.upgrade_to_token(skey, issue_refresh=False, access_grant=_code) atr = AccessTokenResponse(**aresp.to_dict()) aresp = atr _cont = self.sdb[skey] _log_debug("_dic: %s" % _cont) for key, val in _cont.items(): if key in aresp.parameters() and val is not None: aresp[key] = val rtype.remove("token") if len(rtype): return BadRequest("Unknown response type") try: redirect_uri = self.get_redirect_uri(areq) except (RedirectURIError, ParameterError), err: return BadRequest("%s" % err)
# pylint: disable=missing-docstring,no-self-use import six from oic.oauth2.grant import Grant, Token from oic.oauth2.message import AuthorizationResponse from oic.oauth2.message import ErrorResponse from oic.oauth2.message import AccessTokenResponse ATR = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA", token_type="example", refresh_token="tGzv3JOkF0XG5Qx2TlKWIA", example_parameter="example_value", scope=["inner", "outer"]) AR = AuthorizationResponse(code="code", state="state") def _eq(l1, l2): return set(l1) == set(l2) class TestGrant(object): def test_expiration_time(self): grant = Grant() assert grant.exp_in == 600 assert grant.grant_expiration_time == 0 grant = Grant(60) assert grant.exp_in == 60 grant = Grant(-1, AR)
def authz_part2(self, user, areq, skey, permission=None, authn=None, **kwargs): """ After the authentication this is where you should end up :param user: :param areq: The Authorization Request :param skey: Session key :param permission: A permission specification :param authn: The Authentication Method used :param kwargs: possible other parameters :return: A redirect to the redirect_uri of the client """ _log_debug = logger.debug _log_debug("- in authenticated() -") self.sdb.update(skey, "auz", permission) _log_debug("response type: %s" % areq["response_type"]) # create the response aresp = AuthorizationResponse() try: aresp["state"] = areq["state"] except KeyError: pass if "response_type" in areq and \ len(areq["response_type"]) == 1 and \ "none" in areq["response_type"]: pass else: #if self.sdb.is_revoked(sinfo): # return self._error(error="access_denied", # descr="Token is revoked") try: aresp["scope"] = areq["scope"] except KeyError: pass _log_debug("_dic: %s" % self.sdb[skey]) rtype = set(areq["response_type"][:]) if "code" in areq["response_type"]: #if issue_new_code: # scode = self.sdb.duplicate(_sinfo) # _sinfo = self.sdb[scode] _code = aresp["code"] = self.sdb.get_token(skey) rtype.remove("code") else: _code = self.sdb[skey]["code"] self.sdb.update(skey, "code", None) if "token" in rtype: self.sdb.upgrade_to_token(skey, issue_refresh=False, access_grant=_code) atr = AccessTokenResponse(**aresp.to_dict()) aresp = atr _cont = self.sdb[skey] _log_debug("_dic: %s" % _cont) for key, val in _cont.items(): if key in aresp.parameters() and val is not None: aresp[key] = val rtype.remove("token") if len(rtype): return BadRequest("Unknown response type") try: redirect_uri = self.get_redirect_uri(areq) except (RedirectURIError, ParameterError), err: return BadRequest("%s" % err)