def run_auth_server(): try: client_store = ClientStore() client_store.add_client(client_id="abc", client_secret="xyz", redirect_uris=[]) token_store = TokenStore() token_gen = Uuid4() token_gen.expires_in['client_credentials'] = 3600 auth_controller = Provider( access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=token_gen) auth_controller.add_grant(ClientCredentialsGrant()) app = Application(provider=auth_controller) httpd = make_server('', 8080, app, handler_class=OAuthRequestHandler) print("Starting implicit_grant oauth2 server on http://localhost:8080/...") httpd.serve_forever() except KeyboardInterrupt: httpd.server_close()
def run_provider(queue): try: redirect_uri = "http://127.0.0.1:15487/callback" stores = store_factory(client_identifier="abc", client_secret="xyz", redirect_uris=[redirect_uri]) provider = Provider(access_token_store=stores["access_token_store"], auth_code_store=stores["auth_code_store"], client_store=stores["client_store"], site_adapter=TestSiteAdapter(), token_generator=Uuid4()) provider.add_grant(AuthorizationCodeGrant(expires_in=120)) provider.add_grant(RefreshToken(expires_in=60)) app = Wsgi(server=provider) httpd = make_server('', 15486, app, handler_class=NoLoggingHandler) queue.put({"result": 0}) httpd.serve_forever() except Exception as e: queue.put({"result": 1, "error_message": str(e)})
def run_auth_server(): client_store = ClientStore() client_store.add_client(client_id="abc", client_secret="xyz", redirect_uris=["http://localhost:8081/callback"]) token_store = TokenStore() provider = Provider( access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=Uuid4() ) provider.add_grant(AuthorizationCodeGrant(site_adapter=TestSiteAdapter())) try: app = Application( [ url(provider.authorize_path, OAuth2Handler, dict(provider=provider)), url(provider.token_path, OAuth2Handler, dict(provider=provider)), ] ) app.listen(8080) print("Starting OAuth2 server on http://localhost:8080/...") IOLoop.current().start() except KeyboardInterrupt: IOLoop.close()
def run_auth_server(): client_store = ClientStore() # client_store.add_client(client_id="abc", client_secret="xyz", # redirect_uris=["http://localhost:8081/callback"]) client_store.add_client(client_id="abc", client_secret="xyz", redirect_uris=["http://localhost:8080/auth/realms/keycloak-express/broker/oidc/endpoint"]) token_store = TokenStore() provider = Provider(access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=Uuid4()) provider.add_grant(AuthorizationCodeGrant(site_adapter=TestSiteAdapter())) try: app = Application([ url(provider.authorize_path, OAuth2Handler, dict(provider=provider)), url(provider.token_path, OAuth2Handler, dict(provider=provider)), ]) app.listen(8090) print("Starting OAuth2 server on http://localhost:8090/...") IOLoop.current().start() except KeyboardInterrupt: IOLoop.close()
def run_auth_server(): client_store = ClientStore() client_store.add_client(client_id="abc", client_secret="xyz", redirect_uris=["http://10.10.112.59:8081/callback"]) client_store.add_client(client_id="bcd", client_secret="fff", redirect_uris=["http://10.10.112.59:50000/callback"]) client_store.add_client(client_id="9fdc2c7a1cee0cca54c150e3e0b822eb", client_secret="zzz", redirect_uris=["http://10.10.112.59:8888/callback"]) token_store = TokenStore() provider = Provider(access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=Uuid4()) provider.add_grant(AuthorizationCodeGrant(site_adapter=TestSiteAdapter())) settings = dict( template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path=os.path.join(os.path.dirname(__file__), "static"), cookie_secret='61oETzKXQAGaYdkL5gEmGEJJFuYh7EQnp2XdTP1o/Vo=', ) try: app = Application([ url(provider.authorize_path, OAuth2Handler, dict(provider=provider)), url(provider.token_path, OAuth2Handler, dict(provider=provider)), url("/", MainHandler), ], **settings) app.listen(8080) print "Starting OAuth2 server on http://10.10.112.59:8080/..." IOLoop.current().start() except KeyboardInterrupt: IOLoop.close()
def create_auth_server(): client_store = ClientStore() client_store.add_client( client_id="alexa.matsuoka", client_secret="xxxx", redirect_uris=[ "https://layla.amazon.com/api/skill/link/M2Q7FOC6AVxxxx", "https://pitangui.amazon.com/api/skill/link/M2Q7FOC6AVxxxx", "https://alexa.amazon.co.jp/api/skill/link/M2Q7FOC6AVxxxx" ]) token_store = TokenStore() token_store.save_token( AccessToken(client_id="alexa.matsuoka", grant_type="authorization_code", user_id="*****@*****.**", token="xxxx")) provider = Provider(access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=Uuid4(), client_authentication_source=http_basic_auth) provider.add_grant( AuthorizationCodeGrant(site_adapter=TestSiteAdapter(), unique_token=True)) app = Application([ url(provider.authorize_path, OAuth2Handler, dict(provider=provider)), url(provider.token_path, OAuth2Handler, dict(provider=provider)), ], debug=False) return app
def run_auth_server(): try: client_store = ClientStore() client_store.add_client(client_id="abc", client_secret="xyz", redirect_uris=["http://localhost:8081/"]) token_store = TokenStore() provider = Provider(access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=Uuid4()) provider.add_grant(ImplicitGrant(site_adapter=TestSiteAdapter())) app = Application(provider=provider) httpd = make_server('', 8080, app) print( "Starting implicit_grant oauth2 server on http://localhost:8080/..." ) httpd.serve_forever() except KeyboardInterrupt: httpd.server_close()
def run_auth_server(): try: client_store = ClientStore() client_store.add_client( client_id="abc", client_secret="xyz", redirect_uris=["http://localhost:8081/callback"]) token_store = TokenStore() auth_controller = Provider(access_token_store=token_store, auth_code_store=token_store, client_store=client_store, site_adapter=TestSiteAdapter(), token_generator=Uuid4()) auth_controller.add_grant(AuthorizationCodeGrant()) app = Wsgi(server=auth_controller) httpd = make_server('', 8080, app, handler_class=OAuthRequestHandler) print( "Starting implicit_grant oauth2 server on http://localhost:8080/..." ) httpd.serve_forever() except KeyboardInterrupt: httpd.server_close()
def run_auth_server(): client_store = ClientStore() client_store.add_client(client_id="abc", client_secret="xyz", redirect_uris=[], authorized_grants=[oauth2.grant.ClientCredentialsGrant.grant_type]) token_store = TokenStore() # Generator of tokens token_generator = oauth2.tokengenerator.Uuid4() token_generator.expires_in[oauth2.grant.ClientCredentialsGrant.grant_type] = 3600 provider = Provider(access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=token_generator) # provider.add_grant(AuthorizationCodeGrant(site_adapter=TestSiteAdapter())) provider.add_grant(ClientCredentialsGrant()) try: app = Application([ url(provider.authorize_path, OAuth2Handler, dict(provider=provider)), url(provider.token_path, OAuth2Handler, dict(provider=provider)), ]) app.listen(8080) print("Starting OAuth2 server on http://localhost:8080/...") IOLoop.current().start() except KeyboardInterrupt: IOLoop.close()
def run_auth_server(certfile): try: client_store = ClientStore() client_store.add_client(client_id="abc", client_secret="xyz", redirect_uris=["http://localhost:8081/callback"]) token_store = TokenStore() auth_controller = Provider( access_token_store=token_store, auth_code_store=token_store, client_store=client_store, site_adapter=TestSiteAdapter(), token_generator=Uuid4()) auth_controller.add_grant(AuthorizationCodeGrant()) app = Wsgi(server=auth_controller) httpd = make_server('', 8080, app, handler_class=OAuthRequestHandler) httpd.socket = ssl.wrap_socket(httpd.socket, certfile=certfile, server_side=True) print("Starting implicit_grant oauth2 server on https://localhost:8080/...") httpd.serve_forever() except KeyboardInterrupt: httpd.server_close()
def run_auth_server(): try: client_store = ClientStore() client_store.add_client(client_id="abc", client_secret="xyz", redirect_uris=[]) token_store = TokenStore() provider = Provider( access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=Uuid4()) provider.add_grant( ResourceOwnerGrant(site_adapter=TestSiteAdapter()) ) app = Application(provider=provider) httpd = make_server('', 8080, app) print("Starting OAuth2 server on http://localhost:8080/...") httpd.serve_forever() except KeyboardInterrupt: httpd.server_close()
def make_application(token_store, client_store, token_gen): auth_controller = Provider(access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=token_gen) auth_controller.add_grant(ClientCredentialsGrant()) return Application(provider=auth_controller)
def make_application(token_store, client_store, token_gen): auth_controller = Provider( access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=token_gen) auth_controller.add_grant(ClientCredentialsGrant()) return Application(provider=auth_controller)
def make_application(token_store, client_store, token_gen): provider = Provider( access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=token_gen, ) provider.add_grant(ResourceOwnerGrant(expires_in=3600, site_adapter=TestSiteAdapter())) return Application(provider=provider)
def setUp(self): self.client_store_mock = Mock(spec=ClientStore) self.token_generator_mock = Mock() self.token_generator_mock.expires_in = {} self.token_generator_mock.refresh_expires_in = 0 self.auth_server = Provider(access_token_store=Mock(), auth_code_store=Mock(), client_store=self.client_store_mock, site_adapter=Mock(), token_generator=self.token_generator_mock, response_class=Mock())
def make_application(token_store, client_store, token_gen): provider = Provider( access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=token_gen) provider.add_grant( ResourceOwnerGrant( expires_in=3600, site_adapter=TestSiteAdapter()) ) return Application(provider=provider)
def setUp(self): self.client_store_mock = Mock(spec=ClientStore) self.token_generator_mock = Mock() self.response_mock = Mock(spec=Response) self.response_mock.body = "" response_class_mock = Mock(return_value=self.response_mock) self.token_generator_mock.expires_in = {} self.token_generator_mock.refresh_expires_in = 0 self.auth_server = Provider(access_token_store=Mock(), auth_code_store=Mock(), client_store=self.client_store_mock, token_generator=self.token_generator_mock, response_class=response_class_mock)
def setUp(self): self.client_store_mock = Mock(spec=ClientStore) self.token_generator_mock = Mock() self.auth_server = Provider(access_token_store=Mock(), auth_code_store=Mock(), client_store=self.client_store_mock, site_adapter=Mock(), token_generator=self.token_generator_mock, response_class=Mock())
def get(self): try: client_store = ClientStore() client_store.add_client(client_id="abc", client_secret="xyz", redirect_uris=[], authorized_grants=[oauth2.grant.ClientCredentialsGrant.grant_type]) token_store = TokenStore() # Generator of tokens token_generator = oauth2.tokengenerator.Uuid4() token_generator.expires_in[oauth2.grant.ClientCredentialsGrant.grant_type] = 3600 provider = Provider(access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=token_generator) # provider.add_grant(AuthorizationCodeGrant(site_adapter=TestSiteAdapter())) provider.add_grant(ClientCredentialsGrant()) except StandardError,e: result = {"success":0,"return_code":str(e),"error_msg":utils.format_error()}
def run_auth_server(port=8282): print("Starting OAuth2 server on port:" + str(port)) client_store = ClientStore() client_store.add_client(client_id="abc", client_secret="xyz", redirect_uris=["http://0.0.0.0:5000/"]) token_store = TokenStore() provider = Provider(access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=Uuid4()) provider.add_grant(AuthorizationCodeGrant(site_adapter=TestSiteAdapter())) app = Application(provider=provider) httpd = make_server('', port, app, handler_class=OAuthRequestHandler) httpd.serve_forever()
def run_provider(queue): try: redirect_uri = "http://127.0.0.1:15487/callback" stores = store_factory(client_identifier="abc", client_secret="xyz", redirect_uris=[redirect_uri]) provider = Provider( access_token_store=stores["access_token_store"], auth_code_store=stores["auth_code_store"], client_store=stores["client_store"], site_adapter=TestSiteAdapter(), token_generator=Uuid4()) provider.add_grant(AuthorizationCodeGrant(expires_in=120)) provider.add_grant(RefreshToken(expires_in=60)) app = Wsgi(server=provider) httpd = make_server('', 15486, app, handler_class=NoLoggingHandler) queue.put({"result": 0}) httpd.serve_forever() except Exception as e: queue.put({"result": 1, "error_message": str(e)})
def run_auth_server(): try: client = MongoClient('localhost', 27017) db = client.test_database client_store = ClientStore(collection=db["clients"]) token_store = AccessTokenStore(collection=db["access_tokens"]) code_store = AuthCodeStore(collection=db["auth_codes"]) provider = Provider( access_token_store=token_store, auth_code_store=code_store, client_store=client_store, token_generator=Uuid4()) provider.add_grant( AuthorizationCodeGrant(site_adapter=TestSiteAdapter(), scopes=["basic", "big", "long"], unique_token=True, expires_in=20 ) ) provider.add_grant( RefreshToken(scopes=["basic", "big", "long"], expires_in=2592000, reissue_refresh_tokens=True) ) app = Application(provider=provider) httpd = make_server('', 8080, app, handler_class=OAuthRequestHandler) print("Starting OAuth2 server on http://localhost:8080/...") httpd.serve_forever() except KeyboardInterrupt: httpd.server_close()
def create_provider(): redirect_uri = "http://127.0.0.1:15487/callback" stores = store_factory(client_identifier="abc", client_secret="xyz", redirect_uris=[redirect_uri]) provider = Provider(access_token_store=stores["access_token_store"], auth_code_store=stores["auth_code_store"], client_store=stores["client_store"], token_generator=Uuid4()) provider.add_grant( AuthorizationCodeGrant( expires_in=120, site_adapter=TestSiteAdapter() ) ) provider.add_grant(RefreshToken(expires_in=60)) return provider
def get(self): try: client_store = ClientStore() client_store.add_client(client_id="abc", client_secret="xyz", redirect_uris=[], authorized_grants=[oauth2.grant.ClientCredentialsGrant.grant_type]) token_store = TokenStore() # Generator of tokens token_generator = oauth2.tokengenerator.Uuid4() token_generator.expires_in[oauth2.grant.ClientCredentialsGrant.grant_type] = 3600 provider = Provider(access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=token_generator) # provider.add_grant(AuthorizationCodeGrant(site_adapter=TestSiteAdapter())) provider.add_grant(ClientCredentialsGrant()) except Exception as e: result = {"success":0,"return_code":unicode(e),"error_msg":utils.format_error()} self.finish(result)
def run_auth_server(): try: client_store = ClientStore() client_store.add_client(client_id="abc", client_secret="xyz", redirect_uris=["http://localhost:8081/callback"]) token_store = TokenStore() provider = Provider( access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=Uuid4(), ) provider.add_grant(AuthorizationCodeGrant(site_adapter=TestSiteAdapter())) app = Application(provider=provider) httpd = make_server("", 8080, app, handler_class=OAuthRequestHandler) print("Starting OAuth2 server on http://localhost:8080/...") httpd.serve_forever() except KeyboardInterrupt: httpd.server_close()
def run_auth_server(): try: client_store = ClientStore() client_store.add_client(client_id="abc", client_secret="xyz", redirect_uris=["http://localhost:8081/"]) token_store = TokenStore() auth_server = Provider( access_token_store=token_store, auth_code_store=token_store, client_store=client_store, site_adapter=TestSiteAdapter(), token_generator=Uuid4()) auth_server.add_grant(ImplicitGrant()) app = Wsgi(server=auth_server) httpd = make_server('', 8080, app) print("Starting implicit_grant oauth2 server on http://localhost:8080/...") httpd.serve_forever() except KeyboardInterrupt: httpd.server_close()
def make_provider(session_factory, url_prefix, login_url): """Make an OAuth provider""" token_store = AccessTokenStore(session_factory) code_store = AuthCodeStore(session_factory) client_store = ClientStore(session_factory) provider = Provider( access_token_store=token_store, auth_code_store=code_store, client_store=client_store, token_generator=UUID4(), ) provider.token_path = url_path_join(url_prefix, 'token') provider.authorize_path = url_path_join(url_prefix, 'authorize') site_adapter = JupyterHubSiteAdapter(login_url=login_url) provider.add_grant(AuthorizationCodeGrant(site_adapter=site_adapter)) return provider
def create_provider(): redirect_uri = "http://127.0.0.1:15487/callback" stores = store_factory(client_identifier="abc", client_secret="xyz", redirect_uris=[redirect_uri]) provider = Provider(access_token_store=stores["access_token_store"], auth_code_store=stores["auth_code_store"], client_store=stores["client_store"], token_generator=Uuid4()) provider.add_grant( AuthorizationCodeGrant(expires_in=120, site_adapter=TestSiteAdapter())) provider.add_grant(RefreshToken(expires_in=60)) return provider
def run_auth_server(): try: client = MongoClient('localhost', 27017) db = client.test_database client_store = ClientStore(collection=db["clients"]) # memory # client_store = ClientStore() # client_store.add_client(client_id="abc", client_secret="xyz", # redirect_uris=["http://localhost:8081/callback"]) # # token_store = TokenStore() token_store = AccessTokenStore(collection=db["access_tokens"]) code_store = AuthCodeStore(collection=db["auth_codes"]) provider = Provider(access_token_store=token_store, auth_code_store=code_store, client_store=client_store, token_generator=Uuid4()) provider.add_grant( AuthorizationCodeGrant(site_adapter=TestSiteAdapter(), scopes=["test", "test2"], unique_token=True, expires_in=1)) # auth_controller.add_grant_type(ResourceOwnerGrant(tokens_expire=600)) provider.add_grant( RefreshToken(scopes=["test", "test2"], expires_in=2592000, reissue_refresh_tokens=True)) # auth_controller.add_grant_type(RefreshToken(tokens_expire=1200)) app = Application(provider=provider) httpd = make_server('', 8080, app, handler_class=OAuthRequestHandler) print("Starting OAuth2 server on http://localhost:8080/...") httpd.serve_forever() except KeyboardInterrupt: httpd.server_close()
def main(): token_store = AccessTokenStore() provider = Provider(access_token_store=token_store, auth_code_store=token_store, client_store=AuthUserStore(), token_generator=Uuid4()) provider.add_grant( ResourceOwnerGrant(site_adapter=AuthSiteAdapter(), unique_token=True, expires_in=ACCESS_TOKEN_REDIS_TTL)) provider.add_grant(RefreshToken(expires_in=REFRESH_TOKEN_REDIS_TTL)) app = Application(handlers=[ url(provider.token_path, OAuth2Handler, dict(provider=provider)), url('/validate-token', AuthValidationHandler) ], template_path=TEMPLATE_PATH, static_path=STATIC_PATH, cookie_secret=COOKIE_SECRET) print 'Starting OAuth Server on port %d' % options.port server = HTTPServer(app) server.listen(options.port) IOLoop.current().start()
class AuthorizationControllerTestCase(unittest.TestCase): def setUp(self): self.client_store_mock = Mock(spec=ClientStore) self.token_generator_mock = Mock() self.token_generator_mock.expires_in = {} self.token_generator_mock.refresh_expires_in = 0 self.auth_server = Provider(access_token_store=Mock(), auth_code_store=Mock(), client_store=self.client_store_mock, site_adapter=Mock(), token_generator=self.token_generator_mock, response_class=Mock()) def test_add_grant_set_expire_time(self): """ Provider.add_grant() should set the expiration time on the instance of TokenGenerator """ self.auth_server.add_grant(AuthorizationCodeGrant(expires_in=400)) self.auth_server.add_grant(ResourceOwnerGrant(expires_in=500)) self.auth_server.add_grant(RefreshToken(expires_in=1200)) self.assertEqual( self.token_generator_mock.expires_in[ AuthorizationCodeGrant.grant_type], 400) self.assertEqual( self.token_generator_mock.expires_in[ ResourceOwnerGrant.grant_type], 500) self.assertEqual(self.token_generator_mock.refresh_expires_in, 1200) def test_dispatch(self): environ = {"session": "data"} process_result = "response" request_mock = Mock(spec=Request) response_mock = Mock(spec=Response) response_class_mock = Mock(return_value=response_mock) grant_handler_mock = Mock(spec=["process", "read_validate_params"]) grant_handler_mock.process.return_value = process_result grant_factory_mock = Mock(return_value=grant_handler_mock) self.auth_server.response_class = response_class_mock self.auth_server.site_adapter = Mock(spec=SiteAdapter) self.auth_server.add_grant(grant_factory_mock) result = self.auth_server.dispatch(request_mock, environ) grant_factory_mock.assert_called_with(request_mock, self.auth_server) response_class_mock.assert_called_with() grant_handler_mock.read_validate_params.assert_called_with( request_mock) grant_handler_mock.process.assert_called_with(request_mock, response_mock, environ) self.assertEqual(result, process_result) def test_dispatch_no_grant_type_found(self): error_body = { "error": "unsupported_response_type", "error_description": "Server does not support given response_type" } request_mock = Mock(spec=Request) response_mock = Mock(spec=Response) response_class_mock = Mock(return_value=response_mock) self.auth_server.response_class = response_class_mock result = self.auth_server.dispatch(request_mock, {}) response_mock.add_header.assert_called_with("Content-type", "application/json") self.assertEqual(response_mock.status_code, 400) self.assertEqual(response_mock.body, json.dumps(error_body)) self.assertEqual(result, response_mock)
def main(): parser = argparse.ArgumentParser(description="python-oauth2 test provider") parser.add_argument("--store", dest="store", type=str, default="mongodb", help="The store adapter to use. Can one of 'mongodb'"\ "(default), 'mysql'") args = parser.parse_args() if args.store == "mongodb": print("Using mongodb stores...") client = MongoClient() db = client.testdb access_token_store = AccessTokenStore(collection=db["access_tokens"]) auth_code_store = AuthCodeStore(collection=db["auth_codes"]) client_store = ClientStore(collection=db["clients"]) elif args.store == "mysql": print("Using mysql stores...") connection = mysql.connector.connect(host="127.0.0.1", user="******", passwd="", db="testdb") access_token_store = MysqlAccessTokenStore(connection=connection) auth_code_store = MysqlAuthCodeStore(connection=connection) client_store = MysqlClientStore(connection=connection) else: raise Exception("Unknown store") provider = Provider(access_token_store=access_token_store, auth_code_store=auth_code_store, client_store=client_store, site_adapter=TestSiteAdapter(), token_generator=Uuid4()) provider.add_grant(AuthorizationCodeGrant(expires_in=120)) provider.add_grant(ImplicitGrant()) provider.add_grant(ResourceOwnerGrant()) provider.add_grant(ClientCredentialsGrant()) provider.add_grant(RefreshToken(expires_in=60)) app = Wsgi(server=provider) try: httpd = make_server('', 8888, app) print("Starting test auth server on port 8888...") httpd.serve_forever() except KeyboardInterrupt: httpd.server_close()
class AuthorizationControllerTestCase(unittest.TestCase): def setUp(self): self.client_store_mock = Mock(spec=ClientStore) self.token_generator_mock = Mock() self.auth_server = Provider(access_token_store=Mock(), auth_code_store=Mock(), client_store=self.client_store_mock, site_adapter=Mock(), token_generator=self.token_generator_mock, response_class=Mock()) def test_add_grant_set_expire_time(self): """ Provider.add_grant() should set the expiration time on the instance of TokenGenerator """ self.auth_server.add_grant(RefreshToken(expires_in=600)) self.assertEqual(self.token_generator_mock.expires_in, 600) def test_dispatch(self): environ = {"session": "data"} process_result = "response" request_mock = Mock(spec=Request) response_mock = Mock(spec=Response) response_class_mock = Mock(return_value=response_mock) grant_handler_mock = Mock(spec=["process", "read_validate_params"]) grant_handler_mock.process.return_value = process_result grant_factory_mock = Mock(return_value=grant_handler_mock) self.auth_server.response_class = response_class_mock self.auth_server.site_adapter = Mock(spec=SiteAdapter) self.auth_server.add_grant(grant_factory_mock) result = self.auth_server.dispatch(request_mock, environ) grant_factory_mock.assert_called_with(request_mock, self.auth_server) response_class_mock.assert_called_with() grant_handler_mock.read_validate_params.assert_called_with(request_mock) grant_handler_mock.process.assert_called_with(request_mock, response_mock, environ) self.assertEqual(result, process_result) def test_dispatch_no_grant_type_found(self): error_body = {"error": "unsupported_response_type", "error_description": "Server does not support given response_type"} request_mock = Mock(spec=Request) response_mock = Mock(spec=Response) response_class_mock = Mock(return_value=response_mock) self.auth_server.response_class = response_class_mock result = self.auth_server.dispatch(request_mock, {}) response_mock.add_header.assert_called_with("Content-type", "application/json") self.assertEqual(response_mock.status_code, 400) self.assertEqual(response_mock.body, json.dumps(error_body)) self.assertEqual(result, response_mock)
class ProviderTestCase(unittest.TestCase): def setUp(self): self.client_store_mock = Mock(spec=ClientStore) self.token_generator_mock = Mock() self.response_mock = Mock(spec=Response) self.response_mock.body = "" response_class_mock = Mock(return_value=self.response_mock) self.token_generator_mock.expires_in = {} self.token_generator_mock.refresh_expires_in = 0 self.auth_server = Provider(access_token_store=Mock(), auth_code_store=Mock(), client_store=self.client_store_mock, token_generator=self.token_generator_mock, response_class=response_class_mock) def test_add_grant_set_expire_time(self): """ Provider.add_grant() should set the expiration time on the instance of TokenGenerator """ self.auth_server.add_grant( AuthorizationCodeGrant( expires_in=400, site_adapter=Mock(spec=AuthorizationCodeGrantSiteAdapter))) self.auth_server.add_grant( ResourceOwnerGrant( expires_in=500, site_adapter=Mock(spec=ResourceOwnerGrantSiteAdapter))) self.auth_server.add_grant(RefreshToken(expires_in=1200)) self.assertEqual( self.token_generator_mock.expires_in[ AuthorizationCodeGrant.grant_type], 400) self.assertEqual( self.token_generator_mock.expires_in[ ResourceOwnerGrant.grant_type], 500) self.assertEqual(self.token_generator_mock.refresh_expires_in, 1200) def test_dispatch(self): environ = {"session": "data"} process_result = "response" request_mock = Mock(spec=Request) grant_handler_mock = Mock(spec=["process", "read_validate_params"]) grant_handler_mock.process.return_value = process_result grant_factory_mock = Mock(return_value=grant_handler_mock) self.auth_server.site_adapter = Mock( spec=AuthorizationCodeGrantSiteAdapter) self.auth_server.add_grant(grant_factory_mock) result = self.auth_server.dispatch(request_mock, environ) grant_factory_mock.assert_called_with(request_mock, self.auth_server) grant_handler_mock.read_validate_params.\ assert_called_with(request_mock) grant_handler_mock.process.assert_called_with(request_mock, self.response_mock, environ) self.assertEqual(result, process_result) def test_dispatch_no_grant_type_found(self): error_body = { "error": "unsupported_response_type", "error_description": "Grant not supported" } request_mock = Mock(spec=Request) result = self.auth_server.dispatch(request_mock, {}) self.response_mock.add_header.assert_called_with( "Content-Type", "application/json") self.assertEqual(self.response_mock.status_code, 400) self.assertEqual(self.response_mock.body, json.dumps(error_body)) self.assertEqual(result, self.response_mock) def test_dispatch_no_client_found(self): request_mock = Mock(spec=Request) grant_handler_mock = Mock(spec=GrantHandler) grant_handler_mock.process.side_effect = OAuthInvalidNoRedirectError( error="") grant_factory_mock = Mock(return_value=grant_handler_mock) self.auth_server.add_grant(grant_factory_mock) self.auth_server.dispatch(request_mock, {}) self.response_mock.add_header.assert_called_with( "Content-Type", "application/json") self.assertEqual(self.response_mock.status_code, 400) self.assertEqual( json.loads(self.response_mock.body)["error"], "invalid_redirect_uri") def test_dispatch_general_exception(self): request_mock = Mock(spec=Request) grant_handler_mock = Mock(spec=GrantHandler) grant_handler_mock.process.side_effect = KeyError grant_factory_mock = Mock(return_value=grant_handler_mock) self.auth_server.add_grant(grant_factory_mock) self.auth_server.dispatch(request_mock, {}) self.assertTrue(grant_handler_mock.handle_error.called)
def __init__(self, dbconnection): self.templates = os.path.join(os.path.dirname(__file__), "../templates") self.static = os.path.join(os.path.dirname(__file__), "../static") # DataBase connection self.dbconnection = dbconnection ## # OAuth authentication service (token provider) # Client Store (will be taken from db) client_store = ClientStore() client_store.add_client(client_id="abc", client_secret="xyz", redirect_uris=["http://localhost:8111"]) ## # OAuth Token Store (in memory) token_store = TokenStore() # Generator of tokens token_generator = Uuid4() #token_generator.expires_in[ClientCredentialsGrant.grant_type] = 3600 ## # OAuth Provider provider = Provider(access_token_store=token_store, auth_code_store=token_store, client_store=client_store, token_generator=token_generator) #provider.token_path = '/oauth/token' # Support for the authorization code grant provider.add_grant( AuthorizationCodeGrant(site_adapter=CodeGrant(self.templates))) # provider.add_grant( # ImplicitGrant(site_adapter=Authentication()) # ) logger.debug(provider.authorize_path) logger.debug(provider.token_path) ## # Auth handlers auth_handlers = [ web.url(provider.authorize_path, OAuth2Handler, dict(provider=provider)), web.url(provider.token_path, OAuth2Handler, dict(provider=provider)) ] ## # Web web_handlers = [ web.url(r"/login", login.Index), web.url(r"/logout", logout.Index), web.url(r"/password/(.*)", password.Index), web.url(r"/forgot_password", password.Forgot), web.url(r"/registration", registration.Index), web.url(r'/', home.Index), web.url(r'/settings', home.User), web.url(r'/projects', projects.Projects), web.url(r'/slices/([a-z0-9\._\-]+)', slices.Slices), web.url(r'/users', users.Users), web.url(r'/users/?(' + self.urn_regex + ')', users.Users), web.url(r'/activity', activity.Index), web.url(r'/confirm/(' + self.uuid_regex + ')?', confirm.Index), web.url(r'/status', status.Index), web.url(r'/static/(.*)', web.StaticFileHandler, {'path': self.static}), web.url(r'/test', test.Index), web.url(r"/addOrganization", addOrganization.Index) ] ## # REST API rest_handlers = [ web.url(r'/api/v1/activity?([A-Za-z0-9-]+)?', ActivityHandler), web.url(r'/api/v1/activity/(' + self.uuid_regex + ')?', ActivityHandler), web.url(r'/api/v1/confirm/(' + self.uuid_regex + ')?', ConfirmHandler), web.url(r'/api/v1/requests?([A-Za-z0-9-]+)?', RequestsHandler), web.url(r'/api/v1/requests/(' + self.uuid_regex + ')?', RequestsHandler), web.url(r'/api/v1/usertoken?', UserTokenHandler), web.url(r'/api/v1/login', LoginHandler), web.url(r'/api/v1/password', PasswordHandler), web.url(r'/api/v1/password/(.*)', PasswordHandler), web.url(r'/api/v1/resources$', ResourcesHandler), web.url(r'/api/v1/resources/(' + self.urn_regex + ')?$', ResourcesHandler), web.url(r'/api/v1/resources/(' + self.urn_regex + ')?/?(leases)?$', ResourcesHandler), web.url(r'/api/v1/resources/(' + self.urn_regex + ')?/?(slices)?$', ResourcesHandler), web.url( r'/api/v1/resources/(' + self.urn_regex + ')?/?(testbeds)?$', ResourcesHandler), # leases web.url(r'/api/v1/leases$', LeasesHandler), web.url(r'/api/v1/leases/([A-Za-z0-9-]+)?', LeasesHandler), web.url(r'/api/v1/profile$', ProfileHandler), # testbeds web.url( r'/api/v1/testbeds/?(' + self.urn_regex + ')?/?(resources)?$', TestbedsHandler), web.url(r'/api/v1/testbeds/?(' + self.urn_regex + ')?/?(leases)?$', TestbedsHandler), # users web.url(r'/api/v1/users$', UsersHandler), web.url(r'/api/v1/users/(' + self.email_regex + ')$', UsersHandler), web.url( r'/api/v1/users/?(' + self.urn_regex + ')?/?(authorities|projects|slices)?$', UsersHandler), web.url(r'/api/v1/users/?(authorities|projects|slices)?$', UsersHandler), # authorities web.url(r'/api/v1/authorities$', AuthoritiesHandler), web.url( r'/api/v1/authorities/?(' + self.urn_regex + ')?/?(users|projects)?$', AuthoritiesHandler), # projects web.url( r'/api/v1/projects/?(' + self.urn_regex + ')?/?(users|slices)?$', ProjectsHandler), # slices web.url( r'/api/v1/slices/?(' + self.hrn_regex + ')?/?(users|resources)?$', SlicesHandler), web.url( r'/api/v1/slices/?(' + self.urn_regex + ')?/?(users|resources)?$', SlicesHandler), # F-Interop sessions # security based on the slice id web.url( r'/api/v1/finterop/sessions/?(' + self.urn_regex + ')?/?(start|stop)?$', FinteropSessionsHandler), web.url( r'/api/v1/finterop/sessions/?(' + self.hrn_regex + ')?/?(start|stop)?$', FinteropSessionsHandler), web.url( r'/api/v1/finterop/sessions/?([a-zA-Z0-9]+)?/?(start|stop)?$', FinteropSessionsHandler), #web.url(r'/api/v1/finterop/sessions/?([a-zA-Z0-9]+)?/resources$', ResourceRepoHandler), ] ## # Websockets API # SockJSRouter: configure Websocket WebsocketRouter = SockJSRouter(WebsocketsHandler, '/api/v1/live') ## # URLs handlers handlers = auth_handlers + web_handlers + rest_handlers + WebsocketRouter.urls settings = dict( cookie_secret=config.web["cookie_secret"], login_url="/login", token_secret=config.web["token_secret"], template_path=self.templates, static_path=self.static, #xsrf_cookies=True, debug=True) web.Application.__init__(self, handlers, **settings)
class ProviderTestCase(unittest.TestCase): def setUp(self): self.client_store_mock = Mock(spec=ClientStore) self.token_generator_mock = Mock() self.response_mock = Mock(spec=Response) self.response_mock.body = "" response_class_mock = Mock(return_value=self.response_mock) self.token_generator_mock.expires_in = {} self.token_generator_mock.refresh_expires_in = 0 self.auth_server = Provider(access_token_store=Mock(), auth_code_store=Mock(), client_store=self.client_store_mock, token_generator=self.token_generator_mock, response_class=response_class_mock) def test_add_grant_set_expire_time(self): """ Provider.add_grant() should set the expiration time on the instance of TokenGenerator """ self.auth_server.add_grant( AuthorizationCodeGrant( expires_in=400, site_adapter=Mock(spec=AuthorizationCodeGrantSiteAdapter) ) ) self.auth_server.add_grant( ResourceOwnerGrant( expires_in=500, site_adapter=Mock(spec=ResourceOwnerGrantSiteAdapter) ) ) self.auth_server.add_grant(RefreshToken(expires_in=1200)) self.assertEqual(self.token_generator_mock.expires_in[AuthorizationCodeGrant.grant_type], 400) self.assertEqual(self.token_generator_mock.expires_in[ResourceOwnerGrant.grant_type], 500) self.assertEqual(self.token_generator_mock.refresh_expires_in, 1200) def test_dispatch(self): environ = {"session": "data"} process_result = "response" request_mock = Mock(spec=Request) grant_handler_mock = Mock(spec=["process", "read_validate_params"]) grant_handler_mock.process.return_value = process_result grant_factory_mock = Mock(return_value=grant_handler_mock) self.auth_server.site_adapter = Mock( spec=AuthorizationCodeGrantSiteAdapter ) self.auth_server.add_grant(grant_factory_mock) result = self.auth_server.dispatch(request_mock, environ) grant_factory_mock.assert_called_with(request_mock, self.auth_server) grant_handler_mock.read_validate_params.\ assert_called_with(request_mock) grant_handler_mock.process.assert_called_with(request_mock, self.response_mock, environ) self.assertEqual(result, process_result) def test_dispatch_no_grant_type_found(self): error_body = { "error": "unsupported_response_type", "error_description": "Grant not supported" } request_mock = Mock(spec=Request) result = self.auth_server.dispatch(request_mock, {}) self.response_mock.add_header.assert_called_with("Content-Type", "application/json") self.assertEqual(self.response_mock.status_code, 400) self.assertEqual(self.response_mock.body, json.dumps(error_body)) self.assertEqual(result, self.response_mock) def test_dispatch_no_client_found(self): request_mock = Mock(spec=Request) grant_handler_mock = Mock(spec=GrantHandler) grant_handler_mock.process.side_effect = OAuthInvalidNoRedirectError( error="") grant_factory_mock = Mock(return_value=grant_handler_mock) self.auth_server.add_grant(grant_factory_mock) self.auth_server.dispatch(request_mock, {}) self.response_mock.add_header.assert_called_with("Content-Type", "text/plain") self.assertEqual(self.response_mock.status_code, 400) self.assertEqual(self.response_mock.body, "") def test_dispatch_general_exception(self): request_mock = Mock(spec=Request) grant_handler_mock = Mock(spec=GrantHandler) grant_handler_mock.process.side_effect = KeyError grant_factory_mock = Mock(return_value=grant_handler_mock) self.auth_server.add_grant(grant_factory_mock) self.auth_server.dispatch(request_mock, {}) self.assertTrue(grant_handler_mock.handle_error.called)
def main(): client = MongoClient() db = client.testdb access_token_store = AccessTokenStore(collection=db["access_tokens"]) auth_code_store = AuthCodeStore(collection=db["auth_codes"]) client_store = ClientStore(collection=db["clients"]) provider = Provider(access_token_store=access_token_store, auth_code_store=auth_code_store, client_store=client_store, site_adapter=TestSiteAdapter(), token_generator=Uuid4()) provider.add_grant(AuthorizationCodeGrant()) provider.add_grant(ImplicitGrant()) provider.add_grant(ResourceOwnerGrant()) provider.add_grant(ClientCredentialsGrant()) provider.add_grant(RefreshToken(expires_in=600)) provider.enable_unique_tokens() app = Wsgi(server=provider) try: httpd = make_server('', 8888, app) print("Starting test auth server on port 8888...") httpd.serve_forever() except KeyboardInterrupt: httpd.server_close()
def main(): client = MongoClient() db = client.testdb access_token_store = AccessTokenStore(collection=db["access_tokens"]) auth_code_store = AuthCodeStore(collection=db["auth_codes"]) client_store = ClientStore(collection=db["clients"]) provider = Provider( access_token_store=access_token_store, auth_code_store=auth_code_store, client_store=client_store, site_adapter=TestSiteAdapter(), token_generator=Uuid4(), ) provider.add_grant(AuthorizationCodeGrant()) provider.add_grant(ImplicitGrant()) provider.add_grant(ResourceOwnerGrant()) provider.add_grant(ClientCredentialsGrant()) provider.add_grant(RefreshToken(expires_in=600)) provider.enable_unique_tokens() app = Wsgi(server=provider) try: httpd = make_server("", 8888, app) print("Starting test auth server on port 8888...") httpd.serve_forever() except KeyboardInterrupt: httpd.server_close()