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_token_endpoint(): provider = Provider("pyoicserv", sdb.SessionDB(), CDB, AUTHN_BROKER, AUTHZ, verify_client, symkey=rndstr(16)) authreq = AuthorizationRequest(state="state", redirect_uri="http://example.com/authz", client_id="client1") _sdb = provider.sdb sid = _sdb.token.key(user="******", areq=authreq) access_grant = _sdb.token(sid=sid) _sdb[sid] = { "oauth_state": "authz", "user_id": "user_id", "authzreq": "", "client_id": "client1", "code": access_grant, "code_used": False, "redirect_uri": "http://example.com/authz" } # Construct Access token request areq = AccessTokenRequest(code=access_grant, redirect_uri="http://example.com/authz", client_id="client1", client_secret="hemlighet",) print areq.to_dict() resp = provider.token_endpoint(request=areq.to_urlencoded()) print resp.message atr = AccessTokenResponse().deserialize(resp.message, "json") print atr.keys() assert _eq(atr.keys(), ['access_token', 'expires_in', 'token_type', 'refresh_token'])
def test_token_endpoint(self): authreq = AuthorizationRequest(state="state", redirect_uri="http://example.com/authz", client_id="client1") _sdb = self.provider.sdb sid = _sdb.access_token.key(user="******", areq=authreq) access_grant = _sdb.access_token(sid=sid) _sdb[sid] = { "oauth_state": "authz", "sub": "sub", "authzreq": "", "client_id": "client1", "code": access_grant, "code_used": False, "redirect_uri": "http://example.com/authz" } # Construct Access token request areq = AccessTokenRequest(code=access_grant, redirect_uri="http://example.com/authz", client_id="client1", client_secret="hemlighet", grant_type='authorization_code') with LogCapture(level=logging.DEBUG) as logcap: resp = self.provider.token_endpoint(request=areq.to_urlencoded()) atr = AccessTokenResponse().deserialize(resp.message, "json") assert _eq(atr.keys(), ['access_token', 'token_type', 'refresh_token']) expected = ( 'body: code=<REDACTED>&client_secret=<REDACTED>&grant_type' '=authorization_code' ' &client_id=client1&redirect_uri=http%3A%2F%2Fexample.com%2Fauthz') assert _eq(parse_qs(logcap.records[1].msg[6:]), parse_qs(expected[6:])) expected = {u'code': '<REDACTED>', u'client_secret': '<REDACTED>', u'redirect_uri': u'http://example.com/authz', u'client_id': 'client1', u'grant_type': 'authorization_code'} # Don't try this at home, kids! # We have to eval() to a dict here because otherwise the arbitrary # ordering of the string causes the test to fail intermittently. assert _eq(eval(logcap.records[2].msg[4:]), expected) assert _eq(logcap.records[3].msg, 'Verified Client ID: client1') expected = {'redirect_uri': u'http://example.com/authz', 'client_secret': '<REDACTED>', 'code': u'<REDACTED>', 'client_id': 'client1', 'grant_type': 'authorization_code'} assert eval(logcap.records[4].msg[20:]) == expected expected = {'code': '<REDACTED>', 'authzreq': '', 'sub': 'sub', 'access_token': '<REDACTED>', 'token_type': 'Bearer', 'redirect_uri': 'http://example.com/authz', 'code_used': True, 'client_id': 'client1', 'oauth_state': 'token', 'refresh_token': '<REDACTED>', 'access_token_scope': '?'} assert _eq(eval(logcap.records[5].msg[7:]), expected) expected = {'access_token': u'<REDACTED>', 'token_type': 'Bearer', 'refresh_token': '<REDACTED>'} assert _eq(eval(logcap.records[6].msg[21:]), expected)
def test_to_urlencoded_extended_omit(self): atr = AccessTokenResponse( access_token="2YotnFZFEjr1zCsicMWpAA", token_type="example", expires_in=3600, refresh_token="tGzv3JOkF0XG5Qx2TlKWIA", example_parameter="example_value", scope=["inner", "outer"], extra=["local", "external"], level=3) uec = atr.to_urlencoded() assert query_string_compare(uec, "scope=inner+outer&level=3&expires_in=3600&token_type=example&extra=local&" "extra=external&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA&" "access_token=2YotnFZFEjr1zCsicMWpAA&example_parameter=example_value") del atr["extra"] ouec = atr.to_urlencoded() assert query_string_compare(ouec, "access_token=2YotnFZFEjr1zCsicMWpAA&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA&" "level=3&example_parameter=example_value&token_type=example&expires_in=3600&" "scope=inner+outer") assert len(uec) == (len(ouec) + len("extra=local") + len("extra=external") + 2) atr2 = AccessTokenResponse().deserialize(uec, "urlencoded") assert _eq(atr2.keys(), ['access_token', 'expires_in', 'token_type', 'scope', 'refresh_token', 'level', 'example_parameter', 'extra']) atr3 = AccessTokenResponse().deserialize(ouec, "urlencoded") assert _eq(atr3.keys(), ['access_token', 'expires_in', 'token_type', 'scope', 'refresh_token', 'level', 'example_parameter'])
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_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_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_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_token_endpoint(self): authreq = AuthorizationRequest(state="state", redirect_uri="http://example.com/authz", client_id="client1") _sdb = self.provider.sdb sid = _sdb.access_token.key(user="******", areq=authreq) access_grant = _sdb.access_token(sid=sid) _sdb[sid] = { "oauth_state": "authz", "sub": "sub", "authzreq": "", "client_id": "client1", "code": access_grant, "code_used": False, "redirect_uri": "http://example.com/authz" } # Construct Access token request areq = AccessTokenRequest(code=access_grant, redirect_uri="http://example.com/authz", client_id="client1", client_secret="hemlighet", grant_type='authorization_code') resp = self.provider.token_endpoint(request=areq.to_urlencoded()) atr = AccessTokenResponse().deserialize(resp.message, "json") assert _eq(atr.keys(), ['access_token', 'token_type', 'refresh_token'])
def test_token_endpoint(self): authreq = AuthorizationRequest(state="state", redirect_uri="http://example.com/authz", client_id="client1") _sdb = self.provider.sdb sid = _sdb.access_token.key(user="******", areq=authreq) access_grant = _sdb.token_factory['code'](sid=sid) _sdb[sid] = { "oauth_state": "authz", "sub": "sub", "authzreq": authreq.to_json(), "client_id": "client1", "code": access_grant, "code_used": False, "redirect_uri": "http://example.com/authz", 'response_type': ['code'] } # Construct Access token request areq = AccessTokenRequest(code=access_grant, redirect_uri="http://example.com/authz", client_id="client1", client_secret="hemlighet", grant_type='authorization_code') resp = self.provider.token_endpoint(request=areq.to_urlencoded()) atr = AccessTokenResponse().deserialize(resp.message, "json") assert _eq(atr.keys(), ['access_token', 'token_type'])
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 token_endpoint(self, authn="", **kwargs): """ This is where clients come to get their access tokens """ _sdb = self.sdb logger.debug("- token -") body = kwargs["request"] logger.debug("body: %s" % sanitize(body)) areq = AccessTokenRequest().deserialize(body, "urlencoded") try: self.client_authn(self, areq, authn) except FailedAuthentication as err: logger.error(err) err = TokenErrorResponse(error="unauthorized_client", error_description="%s" % err) return Response(err.to_json(), content="application/json", status="401 Unauthorized") logger.debug("AccessTokenRequest: %s" % sanitize(areq)) try: assert areq["grant_type"] == "authorization_code" except AssertionError: err = TokenErrorResponse(error="invalid_request", error_description="Wrong grant type") return Response(err.to_json(), content="application/json", status="401 Unauthorized") # assert that the code is valid _info = _sdb[areq["code"]] resp = self.token_scope_check(areq, _info) if resp: return resp # If redirect_uri was in the initial authorization request # verify that the one given here is the correct one. if "redirect_uri" in _info: assert areq["redirect_uri"] == _info["redirect_uri"] try: _tinfo = _sdb.upgrade_to_token(areq["code"], issue_refresh=True) except AccessCodeUsed: err = TokenErrorResponse(error="invalid_grant", error_description="Access grant used") return Response(err.to_json(), content="application/json", status="401 Unauthorized") logger.debug("_tinfo: %s" % sanitize(_tinfo)) atr = AccessTokenResponse(**by_schema(AccessTokenResponse, **_tinfo)) logger.debug("AccessTokenResponse: %s" % sanitize(atr)) return Response(atr.to_json(), content="application/json")
def test_token_endpoint(self): authreq = AuthorizationRequest(state="state", redirect_uri="http://example.com/authz", client_id="client1") _sdb = self.provider.sdb sid = _sdb.access_token.key(user="******", areq=authreq) access_grant = _sdb.access_token(sid=sid) _sdb[sid] = { "oauth_state": "authz", "sub": "sub", "authzreq": "", "client_id": "client1", "code": access_grant, "code_used": False, "redirect_uri": "http://example.com/authz" } # Construct Access token request areq = AccessTokenRequest(code=access_grant, redirect_uri="http://example.com/authz", client_id="client1", client_secret="hemlighet", grant_type='authorization_code') with LogCapture(level=logging.DEBUG) as logcap: resp = self.provider.token_endpoint(request=areq.to_urlencoded()) atr = AccessTokenResponse().deserialize(resp.message, "json") assert _eq(atr.keys(), ['access_token', 'token_type', 'refresh_token']) expected = ( 'token_request: code=<REDACTED>&client_secret=<REDACTED>&grant_type=authorization_code' '&client_id=client1&redirect_uri=http%3A%2F%2Fexample.com%2Fauthz') assert _eq(parse_qs(logcap.records[1].msg[15:]), parse_qs(expected[15:])) expected = {u'code': '<REDACTED>', u'client_secret': '<REDACTED>', u'redirect_uri': u'http://example.com/authz', u'client_id': 'client1', u'grant_type': 'authorization_code'} # Don't try this at home, kids! # We have to eval() to a dict here because otherwise the arbitrary # ordering of the string causes the test to fail intermittently. assert _eq(eval(logcap.records[2].msg[4:]), expected) assert _eq(logcap.records[3].msg, 'Verified Client ID: client1') expected = {'redirect_uri': u'http://example.com/authz', 'client_secret': '<REDACTED>', 'code': u'<REDACTED>', 'client_id': 'client1', 'grant_type': 'authorization_code'} assert eval(logcap.records[4].msg[20:]) == expected expected = {'code': '<REDACTED>', 'authzreq': '', 'sub': 'sub', 'access_token': '<REDACTED>', 'token_type': 'Bearer', 'redirect_uri': 'http://example.com/authz', 'code_used': True, 'client_id': 'client1', 'oauth_state': 'token', 'refresh_token': '<REDACTED>', 'access_token_scope': '?'} assert _eq(eval(logcap.records[5].msg[7:]), expected) expected = {'access_token': u'<REDACTED>', 'token_type': 'Bearer', 'refresh_token': '<REDACTED>'} assert _eq(eval(logcap.records[6].msg[21:]), expected)
def token_endpoint(self, authn="", **kwargs): """ This is where clients come to get their access tokens """ _sdb = self.sdb LOG_DEBUG("- token -") body = kwargs["request"] LOG_DEBUG("body: %s" % body) areq = AccessTokenRequest().deserialize(body, "urlencoded") try: client = self.client_authn(self, areq, authn) except FailedAuthentication as err: err = TokenErrorResponse(error="unauthorized_client", error_description="%s" % err) return Response(err.to_json(), content="application/json", status="401 Unauthorized") LOG_DEBUG("AccessTokenRequest: %s" % areq) try: assert areq["grant_type"] == "authorization_code" except AssertionError: err = TokenErrorResponse(error="invalid_request", error_description="Wrong grant type") return Response(err.to_json(), content="application/json", status="401 Unauthorized") # assert that the code is valid _info = _sdb[areq["code"]] resp = self.token_scope_check(areq, _info) if resp: return resp # If redirect_uri was in the initial authorization request # verify that the one given here is the correct one. if "redirect_uri" in _info: assert areq["redirect_uri"] == _info["redirect_uri"] try: _tinfo = _sdb.upgrade_to_token(areq["code"], issue_refresh=True) except AccessCodeUsed: err = TokenErrorResponse(error="invalid_grant", error_description="Access grant used") return Response(err.to_json(), content="application/json", status="401 Unauthorized") LOG_DEBUG("_tinfo: %s" % _tinfo) atr = AccessTokenResponse(**by_schema(AccessTokenResponse, **_tinfo)) LOG_DEBUG("AccessTokenResponse: %s" % atr) return Response(atr.to_json(), content="application/json")
def token_endpoint(self, authn="", **kwargs): """ This is where clients come to get their access tokens """ _sdb = self.sdb logger.debug("- token -") body = kwargs["request"] logger.debug("body: %s" % sanitize(body)) areq = AccessTokenRequest().deserialize(body, "urlencoded") try: self.client_authn(self, areq, authn) except FailedAuthentication as err: logger.error(err) err = TokenErrorResponse(error="unauthorized_client", error_description="%s" % err) return Response(err.to_json(), content="application/json", status_code=401) logger.debug("AccessTokenRequest: %s" % sanitize(areq)) if areq["grant_type"] != "authorization_code": err = TokenErrorResponse(error="invalid_request", error_description="Wrong grant type") return Response(err.to_json(), content="application/json", status="401 Unauthorized") # assert that the code is valid _info = _sdb[areq["code"]] resp = self.token_scope_check(areq, _info) if resp: return resp # If redirect_uri was in the initial authorization request # verify that the one given here is the correct one. if "redirect_uri" in _info and areq["redirect_uri"] != _info["redirect_uri"]: logger.error('Redirect_uri mismatch') err = TokenErrorResponse(error="unauthorized_client") return Unauthorized(err.to_json(), content="application/json") try: _tinfo = _sdb.upgrade_to_token(areq["code"], issue_refresh=True) except AccessCodeUsed: err = TokenErrorResponse(error="invalid_grant", error_description="Access grant used") return Response(err.to_json(), content="application/json", status="401 Unauthorized") logger.debug("_tinfo: %s" % sanitize(_tinfo)) atr = AccessTokenResponse(**by_schema(AccessTokenResponse, **_tinfo)) logger.debug("AccessTokenResponse: %s" % sanitize(atr)) return Response(atr.to_json(), content="application/json", headers=OAUTH2_NOCACHE_HEADERS)
def test_password_grant_type_ok(self): # Set a not so dummy Authn method and token policy self.provider.authn_broker = AUTHN_BROKER2 self.provider.set_token_policy('client1', {'grant_type': ['password']}) areq = ROPCAccessTokenRequest(grant_type='password', username='******', password='******') areq['client_id'] = 'client1' # Token endpoint would fill that in based on client_authn resp = self.provider.password_grant_type(areq) atr = AccessTokenResponse().deserialize(resp.message, "json") assert _eq(atr.keys(), ['access_token', 'token_type', 'refresh_token'])
def test_json_serialize(self): at = AccessTokenResponse(access_token="SlAV32hkKG", token_type="Bearer", expires_in=3600) atj = at.serialize(method="json") atj_obj = json.loads(atj) expected_atj_obj = { "token_type": "Bearer", "access_token": "SlAV32hkKG", "expires_in": 3600 } assert atj_obj == expected_atj_obj
def test_multiple_scope(self): atr = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA", token_type="example", expires_in=3600, refresh_token="tGzv3JOkF0XG5Qx2TlKWIA", example_parameter="example_value", scope=["inner", "outer"]) assert _eq(atr["scope"], ["inner", "outer"]) uec = atr.to_urlencoded() assert "inner+outer" in uec
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_parse_access_token_resp_missing_attribute(self): atresp = AccessTokenResponse( access_token="SlAV32hkKG", token_type="Bearer", refresh_token="8xLOxBtZp8", expire_in=3600 ) atdict = atresp.to_dict() del atdict["access_token"] # remove required access_token atj = json.dumps(atdict) with pytest.raises(MissingRequiredAttribute): self.client.parse_response(AccessTokenResponse, info=atj) with pytest.raises(MissingRequiredAttribute): self.client.parse_response(AccessTokenResponse, info=urlencode(atdict), sformat="urlencoded")
def test_multiple_scope(self): atr = AccessTokenResponse( access_token="2YotnFZFEjr1zCsicMWpAA", token_type="example", expires_in=3600, refresh_token="tGzv3JOkF0XG5Qx2TlKWIA", example_parameter="example_value", scope=["inner", "outer"]) assert _eq(atr["scope"], ["inner", "outer"]) uec = atr.to_urlencoded() assert "inner+outer" in uec
def test_password_grant_type_ok(self): # Set a not so dummy Authn method and token policy self.provider.authn_broker = AUTHN_BROKER2 self.provider.set_token_policy("client1", {"grant_type": ["password"]}) areq = ROPCAccessTokenRequest(grant_type="password", username="******", password="******") areq[ "client_id"] = "client1" # Token endpoint would fill that in based on client_authn resp = self.provider.password_grant_type(areq) atr = AccessTokenResponse().deserialize(resp.message, "json") assert _eq(atr.keys(), ["access_token", "token_type", "refresh_token"])
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_parse_access_token_resp_missing_attribute(self): atresp = AccessTokenResponse(access_token="SlAV32hkKG", token_type="Bearer", refresh_token="8xLOxBtZp8", expire_in=3600) atdict = atresp.to_dict() del atdict["access_token"] # remove required access_token atj = json.dumps(atdict) with pytest.raises(MissingRequiredAttribute): self.client.parse_response(AccessTokenResponse, info=atj) with pytest.raises(MissingRequiredAttribute): self.client.parse_response(AccessTokenResponse, info=urlencode(atdict), sformat='urlencoded')
def test_parse_access_token_resp(self): atr = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA", token_type="example", expires_in=3600, refresh_token="tGzv3JOkF0XG5Qx2TlKWIA", example_parameter="example_value") self.client.parse_response(AccessTokenResponse, info=json.dumps(atr.to_dict())) _grant = self.client.grant[""] assert len(_grant.tokens) == 1 token = _grant.tokens[0] assert token.access_token == "2YotnFZFEjr1zCsicMWpAA" assert token.token_type == "example" assert token.expires_in == 3600 assert token.refresh_token == "tGzv3JOkF0XG5Qx2TlKWIA"
def token_endpoint(self, environ, start_response): """ This is where clients come to get their access tokens """ _sdb = self.sdb LOG_DEBUG("- token -") body = get_post(environ) LOG_DEBUG("body: %s" % body) areq = AccessTokenRequest().deserialize(body, "urlencoded") # Client is from basic auth or ... client = None try: client = self.function["verify_client"](environ, client, self.cdb) except (KeyError, AttributeError): err = TokenErrorResponse(error="unathorized_client", error_description="client_id:%s" % client) resp = Response(err.to_json(), content="application/json", status="401 Unauthorized") return resp(environ, start_response) LOG_DEBUG("AccessTokenRequest: %s" % areq) assert areq["grant_type"] == "authorization_code" # assert that the code is valid _info = _sdb[areq["code"]] # If redirect_uri was in the initial authorization request # verify that the one given here is the correct one. if "redirect_uri" in _info: assert areq["redirect_uri"] == _info["redirect_uri"] _tinfo = _sdb.update_to_token(areq["code"]) LOG_DEBUG("_tinfo: %s" % _tinfo) atr = AccessTokenResponse(**by_schema(AccessTokenResponse, **_tinfo)) LOG_DEBUG("AccessTokenResponse: %s" % atr) resp = Response(atr.to_json(), content="application/json") return resp(environ, start_response)
def test_to_urlencoded_extended_omit(self): atr = AccessTokenResponse( access_token="2YotnFZFEjr1zCsicMWpAA", token_type="example", expires_in=3600, refresh_token="tGzv3JOkF0XG5Qx2TlKWIA", example_parameter="example_value", scope=["inner", "outer"], extra=["local", "external"], level=3) uec = atr.to_urlencoded() assert query_string_compare(uec, "scope=inner+outer&level=3&expires_in=3600&token_type=example&extra=local&extra=external&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA&access_token=2YotnFZFEjr1zCsicMWpAA&example_parameter=example_value") del atr["extra"] ouec = atr.to_urlencoded() assert query_string_compare(ouec, "access_token=2YotnFZFEjr1zCsicMWpAA&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA&level=3&example_parameter=example_value&token_type=example&expires_in=3600&scope=inner+outer") assert len(uec) == (len(ouec) + len("extra=local") + len("extra=external") + 2) atr2 = AccessTokenResponse().deserialize(uec, "urlencoded") assert _eq(atr2.keys(), ['access_token', 'expires_in', 'token_type', 'scope', 'refresh_token', 'level', 'example_parameter', 'extra']) atr3 = AccessTokenResponse().deserialize(ouec, "urlencoded") assert _eq(atr3.keys(), ['access_token', 'expires_in', 'token_type', 'scope', 'refresh_token', 'level', 'example_parameter'])
def test_token_endpoint(): provider = Provider("pyoicserv", sdb.SessionDB(), CDB, AUTHN_BROKER, AUTHZ, verify_client, symkey=rndstr(16)) authreq = AuthorizationRequest(state="state", redirect_uri="http://example.com/authz", client_id="client1") _sdb = provider.sdb sid = _sdb.token.key(user="******", areq=authreq) access_grant = _sdb.token(sid=sid) _sdb[sid] = { "oauth_state": "authz", "sub": "sub", "authzreq": "", "client_id": "client1", "code": access_grant, "code_used": False, "redirect_uri": "http://example.com/authz" } # Construct Access token request areq = AccessTokenRequest( code=access_grant, redirect_uri="http://example.com/authz", client_id="client1", client_secret="hemlighet", ) print areq.to_dict() resp = provider.token_endpoint(request=areq.to_urlencoded()) print resp.message atr = AccessTokenResponse().deserialize(resp.message, "json") print atr.keys() assert _eq(atr.keys(), ['access_token', 'expires_in', 'token_type', 'refresh_token'])
def token_response(**kwargs): _areq = kwargs["areq"] _scode = kwargs["scode"] _sdb = kwargs["sdb"] _dic = _sdb.upgrade_to_token(_scode, issue_refresh=False) aresp = AccessTokenResponse(**by_schema(AccessTokenResponse, **_dic)) if "state" in _areq: aresp["state"] = _areq["state"] return aresp
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_delete_unknown(self): grant = Grant() grant.update(ATR) atr = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA", token_type="example", refresh_token="tGzv3JOkF0XG5Qx2TlKWIA", xscope=["inner", "outer"]) token = Token(atr) grant.delete_token(token) assert len(grant.tokens) == 1
def test_token_revocation_and_introspection(self): authreq = AuthorizationRequest(state="state", redirect_uri="http://example.com/authz", client_id="client1") _sdb = self.provider.sdb sid = _sdb.access_token.key(user="******", areq=authreq) access_grant = _sdb.token_factory["code"](sid=sid) _sdb[sid] = { "oauth_state": "authz", "sub": "sub", "authzreq": authreq.to_json(), "client_id": "client1", "code": access_grant, "code_used": False, "redirect_uri": "http://example.com/authz", "response_type": ["code"], } # Construct Access token request areq = AccessTokenRequest( code=access_grant, redirect_uri="http://example.com/authz", client_id="client1", client_secret="hemlighet", grant_type="authorization_code", ) resp = self.provider.token_endpoint(request=areq.to_urlencoded()) atr = AccessTokenResponse().deserialize(resp.message, "json") req = TokenRevocationRequest( token=atr["access_token"], client_id="client1", client_secret="hemlighet", token_type_hint="access_token", ) resp = self.provider.revocation_endpoint(request=req.to_urlencoded()) assert resp.status_code == 200 req2 = TokenIntrospectionRequest( token=atr["access_token"], client_id="client1", client_secret="hemlighet", token_type_hint="access_token", ) resp = self.provider.introspection_endpoint( request=req2.to_urlencoded()) assert resp ti_resp = TokenIntrospectionResponse().deserialize( resp.message, "json") assert ti_resp["active"] is False
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_token_endpoint(): provider = Provider("pyoicserv", sdb.SessionDB(), CDB, FUNCTIONS) authreq = AuthorizationRequest(state="state", redirect_uri="http://example.com/authz", client_id="client1") _sdb = provider.sdb sid = _sdb.token.key(user="******", areq=authreq) access_grant = _sdb.token(sid=sid) _sdb[sid] = { "oauth_state": "authz", "user_id": "user_id", "authzreq": "", "client_id": "client1", "code": access_grant, "code_used": False, "redirect_uri":"http://example.com/authz" } # Construct Access token request areq = AccessTokenRequest(code=access_grant, redirect_uri="http://example.com/authz") str = areq.to_urlencoded() fil = StringIO.StringIO(buf=str) environ = BASE_ENVIRON.copy() environ["CONTENT_LENGTH"] = len(str) environ["wsgi.input"] = fil environ["REMOTE_USER"] = "******" resp = provider.token_endpoint(environ, start_response) print resp atr = AccessTokenResponse().deserialize(resp[0], "json") print atr.keys() assert _eq(atr.keys(), ['access_token', 'expires_in', 'token_type', 'refresh_token'])
def test_token_introspection_missing(self): authreq = AuthorizationRequest(state="state", redirect_uri="http://example.com/authz", client_id="client2") _sdb = self.provider.sdb self.provider.cdb["client2"] = { "client_secret": "hemlighet", "redirect_uris": [("http://localhost:8087/authz", None)], "token_endpoint_auth_method": "client_secret_post", "response_types": ["code", "token"], } sid = _sdb.access_token.key(user="******", areq=authreq) access_grant = _sdb.token_factory["code"](sid=sid) _sdb[sid] = { "oauth_state": "authz", "sub": "sub", "authzreq": authreq.to_json(), "client_id": "client2", "code": access_grant, "code_used": False, "redirect_uri": "http://example.com/authz", "response_type": ["code"], } # Construct Access token request areq = AccessTokenRequest( code=access_grant, redirect_uri="http://example.com/authz", client_id="client2", client_secret="hemlighet", grant_type="authorization_code", ) resp = self.provider.token_endpoint(request=areq.to_urlencoded()) atr = AccessTokenResponse().deserialize(resp.message, "json") # Delete the client del self.provider.cdb["client2"] req = TokenIntrospectionRequest( token=atr["access_token"], client_id="client2", client_secret="hemlighet", token_type_hint="access_token", ) resp = self.provider.introspection_endpoint( request=req.to_urlencoded()) assert resp ti_resp = TokenIntrospectionResponse().deserialize( resp.message, "json") assert ti_resp["error"] == "unauthorized_client"
def code_grant_type(self, areq): """ Token authorization using Code Grant. RFC6749 section 4.1 """ try: _tinfo = self.sdb.upgrade_to_token(areq["code"], issue_refresh=True) except AccessCodeUsed: error = TokenErrorResponse(error="invalid_grant", error_description="Access grant used") return Unauthorized(error.to_json(), content="application/json") logger.debug("_tinfo: %s" % sanitize(_tinfo)) atr = AccessTokenResponse(**by_schema(AccessTokenResponse, **_tinfo)) logger.debug("AccessTokenResponse: %s" % sanitize(atr)) return Response(atr.to_json(), content="application/json", headers=OAUTH2_NOCACHE_HEADERS)
def token_response(**kwargs): _areq = kwargs["areq"] _scode = kwargs["scode"] _sdb = kwargs["sdb"] _dic = _sdb.upgrade_to_token(_scode, issue_refresh=False) aresp = AccessTokenResponse(**by_schema(AccessTokenResponse, **_dic)) try: aresp["state"] = _areq["state"] except KeyError: pass add_non_standard(_areq, aresp) return aresp
def test_get_access_token_refresh_with_refresh_token(self): self.client.grant["foo"] = Grant() _get = time_util.utc_time_sans_frac() + 60 self.client.grant["foo"].grant_expiration_time = _get self.client.grant["foo"].code = "access_code" resp = AccessTokenResponse(refresh_token="refresh_with_me", access_token="access") token = Token(resp) self.client.grant["foo"].tokens.append(token) # Uses refresh_token from previous response atr = self.client.construct_RefreshAccessTokenRequest(token=token) assert atr["grant_type"] == "refresh_token" assert atr["refresh_token"] == "refresh_with_me"
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 test_construct_TokenRevocationRequest(self): self.client.grant["foo"] = Grant() _get = time_util.utc_time_sans_frac() + 60 self.client.grant["foo"].grant_expiration_time = _get self.client.grant["foo"].code = "access_code" resp = AccessTokenResponse(refresh_token="refresh_with_me", access_token="access") token = Token(resp) self.client.grant["foo"].tokens.append(token) state = "foo" query = "code=SplxlOBeZQQYbYS6WxSbIA&state={}".format(state) self.client.parse_response(AuthorizationResponse, info=query, sformat="urlencoded") req = self.client.construct_TokenRevocationRequest(state=state) assert _eq(req.keys(), ['token']) assert req["token"] == "access"
def test_access_token(self): atr = AccessTokenResponse(access_token="2YotnFZFEjr1zCsicMWpAA", token_type="example", expires_in=-1, refresh_token="tGzv3JOkF0XG5Qx2TlKWIA", example_parameter="example_value", xscope=["inner", "outer"]) token = Token(atr) assert _eq(token.keys(), ['token_expiration_time', 'access_token', 'expires_in', 'example_parameter', 'token_type', 'xscope', 'refresh_token', 'scope', 'replaced']) assert token.access_token == "2YotnFZFEjr1zCsicMWpAA" assert token.token_type == "example" assert token.refresh_token == "tGzv3JOkF0XG5Qx2TlKWIA" assert token.example_parameter == "example_value" assert token.xscope == ["inner", "outer"] assert token.token_expiration_time != 0 assert not token.is_valid()
def test_token_endpoint_ok_state(self): authreq = AuthorizationRequest( state="state", redirect_uri="http://example.com/authz", client_id="client1", response_type="code", scope=["openid"], ) _sdb = self.provider.sdb sid = _sdb.access_token.key(user="******", areq=authreq) access_grant = _sdb.access_token(sid=sid) ae = AuthnEvent("user", "salt") _sdb[sid] = { "oauth_state": "authz", "authn_event": ae.to_json(), "authzreq": "", "client_id": "client1", "code": access_grant, "state": "state", "code_used": False, "scope": ["openid"], "redirect_uri": "http://example.com/authz", } _sdb.do_sub(sid, "client_salt") # Construct Access token request areq = AccessTokenRequest( code=access_grant, client_id="client1", redirect_uri="http://example.com/authz", client_secret="hemlighet", grant_type="authorization_code", state="state", ) txt = areq.to_urlencoded() resp = self.provider.token_endpoint(request=txt) atr = AccessTokenResponse().deserialize(resp.message, "json") assert atr["token_type"] == "Bearer"
# if not self.subset(areq["scope"], _info["scope"]): # LOG_INFO("Asked for scope which is not subset of previous defined") # err = TokenErrorResponse(error="invalid_scope") # return Response(err.to_json(), content="application/json") # If redirect_uri was in the initial authorization request # verify that the one given here is the correct one. if "redirect_uri" in _info: assert areq["redirect_uri"] == _info["redirect_uri"] _tinfo = _sdb.update_to_token(areq["code"]) LOG_DEBUG("_tinfo: %s" % _tinfo) atr = AccessTokenResponse(**by_schema(AccessTokenResponse, **_tinfo)) LOG_DEBUG("AccessTokenResponse: %s" % atr) return Response(atr.to_json(), content="application/json") # ============================================================================= class Endpoint(object): etype = "" def __init__(self, func): self.func = func @property