def test_client_secret_post(): client = Client("A") client.client_secret = "boarding pass" cis = AccessTokenRequest(code="foo", redirect_uri="http://example.com") csp = ClientSecretPost(client) http_args = csp.construct(cis) print cis assert cis["client_id"] == "A" assert cis["client_secret"] == "boarding pass" print http_args assert http_args is None cis = AccessTokenRequest(code="foo", redirect_uri="http://example.com") request_args = {} http_args = csp.construct(cis, request_args, http_args={"client_secret": "another"}) print cis assert cis["client_id"] == "A" assert cis["client_secret"] == "another" print http_args assert http_args == {}
def test_bearer_body(): client = Client("A") client.client_secret = "boarding pass" request_args = {"access_token": "Sesame"} cis = ResourceRequest() http_args = BearerBody(client).construct(cis, request_args) assert cis["access_token"] == "Sesame" print http_args assert http_args is None # ---------- 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" print http_args assert http_args is None
def test_bearer_header_with_http_args(): client = Client("A") client.client_secret = "boarding pass" request_args = {"access_token": "Sesame"} cis = ResourceRequest() bh = BearerHeader(client) http_args = bh.construct(cis, request_args, http_args={"foo": "bar"}) print cis print http_args assert _eq(http_args.keys(), ["foo", "headers"]) assert http_args["headers"] == {"Authorization": "Bearer Sesame"} # ----------------- request_args = {"access_token": "Sesame"} bh = BearerHeader(client) http_args = bh.construct(cis, request_args, http_args={"headers": { "x-foo": "bar" }}) print cis print http_args assert _eq(http_args.keys(), ["headers"]) assert _eq(http_args["headers"].keys(), ["Authorization", "x-foo"]) assert http_args["headers"]["Authorization"] == "Bearer Sesame"
def test_pkce_verify_256(self, session_db_factory): _cli = Client( config={"code_challenge": { "method": "S256", "length": 64 }}) args, cv = _cli.add_code_challenge() authn_broker = AuthnBroker() authn_broker.add("UNDEFINED", DummyAuthn(None, "username")) _prov = Provider( "as", session_db_factory("https://connect-op.heroku.com"), {}, authn_broker, Implicit(), verify_client, ) assert _prov.verify_code_challenge(cv, args["code_challenge"]) is True assert _prov.verify_code_challenge(cv, args["code_challenge"], "S256") is True resp = _prov.verify_code_challenge("XXX", args["code_challenge"]) assert isinstance(resp, Response) assert resp.info()["status_code"] == 401
def create_client(self): self.redirect_uri = "https://example.com/redirect" self.authorization_endpoint = "https://example.com/authz" self.client = Client("1", config={"issuer": "https://example.com/as"}) self.client.redirect_uris = [self.redirect_uri] self.client.authorization_endpoint = self.authorization_endpoint
def create_client(self): self.redirect_uri = "https://example.com/redirect" self.authorization_endpoint = "https://example.com/authz" self.client = Client("1", config={'issuer': 'https://example.com/as'}) self.client.redirect_uris = [self.redirect_uri] self.client.response_type = "code" self.client.authorization_endpoint = self.authorization_endpoint
def create_client(self): self.redirect_uri = "https://example.com/redirect" self.authorization_endpoint = "https://example.com/authz" self.client = Client("1") # pylint: disable=attribute-defined-outside-init self.client.redirect_uris = [self.redirect_uri] self.client.response_type = "code" self.client.authorization_endpoint = self.authorization_endpoint
def test_get_authorization_request(): client = Client() client.redirect_uris = ["https://www.example.com/authz"] client.client_id = "a1b2c3" args = {"response_type": ["code"]} ar = client.construct_AuthorizationRequest(request_args=args) assert ar["client_id"] == 'a1b2c3' assert ar["redirect_uri"] == 'https://www.example.com/authz' assert ar["response_type"] == ['code'] client = Client() client.client_id = "a1b2c3" args = {"response_type": ["code"], "redirect_uri": "https://www.example.com/authz"} ar = client.construct_AuthorizationRequest(request_args=args) assert ar["client_id"] == 'a1b2c3' assert ar["redirect_uri"] == 'https://www.example.com/authz' assert ar["response_type"] == ['code']
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_pkce_create(self): _cli = Client( config={'code_challenge': { 'method': 'S256', 'length': 64 }}) args, cv = _cli.add_code_challenge() assert args['code_challenge_method'] == 'S256' assert _eq(list(args.keys()), ['code_challenge_method', 'code_challenge'])
def test_pkce_create(self): _cli = Client( config={"code_challenge": { "method": "S256", "length": 64 }}) args, cv = _cli.add_code_challenge() assert args["code_challenge_method"] == "S256" assert _eq(list(args.keys()), ["code_challenge_method", "code_challenge"])
def test_client_secret_basic(): client = Client("A") client.client_secret = "boarding pass" cis = AccessTokenRequest(code="foo", redirect_uri="http://example.com") csb = ClientSecretBasic(client) http_args = csb.construct(cis) assert http_args == {"headers": {'Authorization': 'Basic %s' % base64.b64encode('A:boarding pass')}}
def test_get_access_token_request(): resp = AuthorizationResponse(code="code", state="state") grant = Grant(1) grant.add_code(resp) client = Client() client.grant["openid"] = grant time.sleep(2) try: client.construct_AccessTokenRequest(state="openid") except Exception, err: assert err.__class__.__name__ == "GrantExpired"
def test_client_get_grant(): cli = Client() resp = AuthorizationResponse(code="code", state="state") grant = Grant() grant.add_code(resp) cli.grant["state"] = grant gr1 = cli.grant_from_state("state") assert gr1.code == "code"
def phaseN(self, environ, info, server_env, sid): session = server_env["CACHE"][sid] callback = server_env["base_url"] + self.social_endpoint client = Client(client_id=self.client_id, client_authn_method=CLIENT_AUTHN_METHOD) response = client.parse_response(AuthorizationResponse, info, "dict") logger.info("Response: %s" % response) if isinstance(response, ErrorResponse): logger.info("%s" % response) session["authentication"] = "FAILED" return False, "Authentication failed or permission not granted" req_args = { "redirect_uri": callback, "client_secret": self.client_secret, } client.token_endpoint = self.extra["token_endpoint"] tokenresp = client.do_access_token_request( scope=self._scope, body_type=self.token_response_body_type, request_args=req_args, authn_method="client_secret_post", state=response["state"], response_cls=self.access_token_response) if isinstance(tokenresp, ErrorResponse): logger.info("%s" % tokenresp) session["authentication"] = "FAILED" return False, "Authentication failed or permission not granted" # Download the user profile and cache a local instance of the # basic profile info result = client.fetch_protected_resource( self.userinfo_endpoint(tokenresp), token=tokenresp["access_token"]) logger.info("Userinfo: %s" % result.text) profile = json.loads(result.text) logger.info("PROFILE: %s" % (profile, )) session["service"] = self.name session["authentication"] = "OK" session["status"] = "SUCCESS" session["authn_auth"] = self.authenticating_authority session["permanent_id"] = profile["id"] server_env["CACHE"][sid] = session return True, self.convert(profile), session
def test_bearer_header_2(): client = Client("A") client.client_secret = "boarding pass" bh = BearerHeader(client) cis = ResourceRequest(access_token="Sesame") http_args = bh.construct(cis) print cis assert "access_token" not in cis print http_args assert http_args == {"headers": {"Authorization": "Bearer Sesame"}}
def test_pkce_verify_512(self, session_db_factory): _cli = Client(config={'code_challenge': {'method': 'S512', 'length': 96}}) args, cv = _cli.add_code_challenge() authn_broker = AuthnBroker() authn_broker.add("UNDEFINED", DummyAuthn(None, "username")) _prov = Provider("as", session_db_factory('https://connect-op.heroku.com'), {}, authn_broker, Implicit(), verify_client) assert _prov.verify_code_challenge(cv, args['code_challenge'], 'S512') is True resp = _prov.verify_code_challenge('XXX', args['code_challenge']) assert isinstance(resp, Response) assert resp.info()['status_code'] == 401
def test_private_key_jwt(): cli = Client("FOO") cli.token_endpoint = "https://example.com/token" cli.keyjar[""] = KC_RSA cis = AccessTokenRequest() pkj = PrivateKeyJWT(cli) http_args = pkj.construct(cis, algorithm="RS256") assert http_args == {} cas = cis["client_assertion"] header, claim, crypto, header_b64, claim_b64 = jwkest.unpack(cas) jso = json.loads(claim) assert _eq(jso.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"]) print header assert header == {'alg': 'RS256'}
def test_client_parse_extra_args(): cli = Client() args = { "response_type": "", "client_id": "client_id", "redirect_uri": "http://example.com/authz", "scope": "scope", "state": "state", "extra_session": "home" } ar_args = cli._parse_args(AuthorizationRequest, **args) assert _eq(ar_args.keys(), ['state', 'redirect_uri', 'response_type', 'client_id', 'scope', 'extra_session'])
def test_parse_access_token_response_missing_attribute(): at = AccessTokenResponse(access_token="SlAV32hkKG", token_type="Bearer", refresh_token="8xLOxBtZp8", expire_in=3600) atdict = at.to_dict() del atdict["access_token"] atj = json.dumps(atdict) print atj client = Client() ATR = AccessTokenResponse try: client.parse_response(ATR, info=atj) except Exception, err: assert err.__class__.__name__ == "MissingRequiredAttribute"
def test_parse_access_token_response(): client = Client() at = AccessTokenResponse(access_token="SlAV32hkKG", token_type="Bearer", refresh_token="8xLOxBtZp8", expire_in=3600) atj = at.to_json() ATR = AccessTokenResponse atr = client.parse_response(ATR, info=atj) assert _eq(atr.keys(), ['access_token', 'token_type', u'expire_in', 'refresh_token']) uec = at.to_urlencoded() raises(ValueError, 'client.parse_response(ATR, info=uec)') uatr = client.parse_response(ATR, info=uec, sformat="urlencoded") assert _eq(uatr.keys(), ['access_token', 'token_type', 'expire_in', 'refresh_token']) huec = "%s?%s" % ("https://example.com/token", uec) uatr = client.parse_response(ATR, info=huec, sformat="urlencoded") assert _eq(uatr.keys(), ['access_token', 'token_type', 'expire_in', 'refresh_token']) err = ErrorResponse(error="invalid_request", error_description="Something was missing", error_uri="http://example.com/error_message.html") jerr = err.to_json() uerr = err.to_urlencoded() _ = client.parse_response(ATR, info=jerr) _ = client.parse_response(ATR, info=uerr, sformat="urlencoded") raises(Exception, 'client.parse_response(ATR, info=jerr, sformat="urlencoded")') raises(Exception, "client.parse_response(ATR, info=uerr)") raises(Exception, 'client.parse_response(ATR, info=jerr, sformat="focus")')
def test_bearer_body_get_token(): client = Client("A") client.client_secret = "boarding pass" 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_device_flow(): _client = Client() cli = DeviceFlowClient(_client) _server = Server() srv = DeviceFlowServer(_server) # init req = AuthorizationRequest(client_id=cli.host.client_id, response_type='device_code') resp = srv.device_endpoint(req) # Polling req = TokenRequest( grant_type="urn:ietf:params:oauth:grant-type:device_code", device_code=resp['device_dode'], client_id=cli.host.client_id) resp = srv.token_endpoint(req)
def test_client_endpoint(): cli = Client() cli.authorization_endpoint = "https://example.org/oauth2/as" cli.token_endpoint = "https://example.org/oauth2/token" cli.token_revocation_endpoint = "https://example.org/oauth2/token_rev" ae = cli._endpoint("authorization_endpoint") assert ae == "https://example.org/oauth2/as" te = cli._endpoint("token_endpoint") assert te == "https://example.org/oauth2/token" tre = cli._endpoint("token_revocation_endpoint") assert tre == "https://example.org/oauth2/token_rev" ae = cli._endpoint("authorization_endpoint", **{"authorization_endpoint": "https://example.com/as"}) assert ae == "https://example.com/as" cli.token_endpoint = "" raises(Exception, 'cli._endpoint("token_endpoint")') raises(Exception, 'cli._endpoint("foo_endpoint")')
def test_bearer_header_3(): client = Client("A") client.client_secret = "boarding pass" 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() http_args = BearerHeader(client).construct(cis, state="state") print cis assert "access_token" not in cis print http_args assert http_args == {"headers": {"Authorization": "Bearer token1"}}
def test_client_secret_jwt(): cli = Client("Foo") cli.token_endpoint = "https://example.com/token" cli.client_secret = "foobar" csj = ClientSecretJWT(cli) cis = AccessTokenRequest() http_args = csj.construct(cis, algorithm="HS256") print http_args assert cis["client_assertion_type"] == JWT_BEARER assert "client_assertion" in cis cas = cis["client_assertion"] _jwt = JWT().unpack(cas) jso = json.loads(_jwt.part[1]) assert _eq(jso.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"]) print _jwt.headers assert _jwt.headers == {'alg': 'HS256'} _rj = JWS() info = _rj.verify_compact(cas, [SYMKey(key=cli.client_secret)]) assert _eq(info.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"])
def setup_class(self): self.client = Client("1") self.client.redirect_uris = ["http://example.com/redirect"]
def client(): cli = Client(**CLIENT_CONF) cli.client_secret = "boarding pass" return cli
def client(): cli = Client(client_id="A", config={"issuer": "https://example.com/as"}) cli.client_secret = "boarding pass" return cli
def client(): cli = Client("A") cli.client_secret = "boarding pass" return cli