def app(tmpdir): app = Flask(__name__) app.debug = True shutil.copy("tests/testdata/resource.json", str(tmpdir)) shutil.copy("tests/testdata/permission.json", str(tmpdir)) app.config["API_RESOURCE_JSON"] = join(str(tmpdir), "resource.json") app.config["API_PERMISSION_JSON"] = join(str(tmpdir), "permission.json") def fn_user_role(token): user_id = token["id"] user_roles = ["访客", "普通用户", "管理员"] return user_roles[user_id] api = Api(app) auth = Auth(api, fn_user_role=fn_user_role) class User(Resource): schema_inputs = {"post": {"id": "int(0,2)&required"}} def get(self): return "ok" def post(self, id): return "ok", auth.gen_header({"id": id}) api.add_resource(User) api.add_resource(Permission, auth=auth) app.api = api app.auth = auth return app
def create_app(setting_overrides=None): # Define the WSGI application object application = Flask(__name__, static_url_path='/s', static_folder='./static') # Configurations application.config.from_object(settings) application.config['JWT_TOKEN_LOCATION'] = ['cookies'] # store token in cookies application.config['JWT_COOKIE_SECURE'] = True # cookies can only be sent over https application.config['JWT_ACCESS_COOKIE_PATH'] = '' application.config['JWT_SECRET_KEY'] = settings.SECRET_KEY # using default secret key application.config['CORS_HEADERS'] = 'Content-Type' application.config["SESSION_COOKIE_SECURE"] = os.getenv( "SESSION_COOKIE_SECURE", False ) application.secret_key = os.getenv("SECRET_KEY", "default_secret_key") if setting_overrides: application.config.update(setting_overrides) auth_config = AuthConfig.from_env() oauth_client = new_oauth_client(auth_config) application.auth = Auth(auth_config, oauth_client, session) add_error_handlers(application) add_blueprints(application) # Run with proxyfix when behind ELB as SSL is done at the load balancer if application.config["SESSION_COOKIE_SECURE"]: return ProxyFix(application, x_for=1, x_host=1) return application
def create_test_app(**kwargs): app = Flask(__name__) app.config['AZURE_OAUTH_TENANCY'] = config['AZURE_OAUTH_TENANCY'] app.config['AZURE_OAUTH_APPLICATION_ID'] = config[ 'AZURE_OAUTH_APPLICATION_ID'] app.config['AZURE_OAUTH_CLIENT_APPLICATION_IDS'] = config[ 'AZURE_OAUTH_CLIENT_APPLICATION_IDS'] app.config['TEST_JWKS'] = config['TEST_JWKS'] app.auth = TestFlaskAzureOauth( azure_tenancy_id=app.config['AZURE_OAUTH_TENANCY'], azure_application_id=app.config['AZURE_OAUTH_APPLICATION_ID'], azure_client_application_ids=app. config['AZURE_OAUTH_CLIENT_APPLICATION_IDS'], azure_jwks=app.config['TEST_JWKS'].jwks()) # Support invalid ways of setting up the auth provider when testing if 'AUTH_MODE' in kwargs: if kwargs['AUTH_MODE'] == 'null-jwks': app.auth.use_null_jwks() elif kwargs['AUTH_MODE'] == 'broken-jwks': app.auth.use_broken_jwks() elif kwargs['AUTH_MODE'] == 'replaced-jwks': app.auth.use_replaced_jwks() elif kwargs['AUTH_MODE'] == 'restored-jwks': app.auth.use_restored_jwks() @app.route('/meta/auth/introspection') @app.auth() def meta_auth_introspection(): authorization_header = request.headers.get('authorization') token_string = authorization_header.split('Bearer ')[1] payload = { 'data': { 'token': app.auth.introspect_token(token_string=token_string), 'token-string': token_string } } return jsonify(payload) @app.route('/meta/auth/insufficient-scopes') @app.auth('unobtainable-scope') def meta_auth_insufficient_scopes(): """ Simulates a resource a client doesn't have access to due to not having the correct scopes. In practice it is impossible to access this resource. """ return '', HTTPStatus.NO_CONTENT return app
def get_app(debug=False): app = Flask("Data Slug Server") app.debug = debug app.auth = HTTPBasicAuth() core.set_database_connector(app) users.set_password_validification(app) core.register_routes(app) users.register_routes(app) return app
def create_app(): app = Flask(__name__) app.config.from_pyfile('config.py') app.register_blueprint(root.mod, url_prefix='/') app.register_blueprint(cpdaily.mod, url_prefix='/cpdaily') app.register_blueprint(admin.mod, url_prefix='/wechat-admin') scheduler = APScheduler() scheduler.init_app(app) scheduler.start() with app.app_context(): app.admin = Admin() app.msg_logger = MsgLogger() app.cpdaily = CpDaily() app.auth = Auth() return app
def flask_app(auth): app = Flask(__name__) app.secret_key = "my-secret-key" app.auth = auth @app.route("/") @requires_auth def root(): return "Hello, World!" @app.route("/test-roles") @requires_auth @requires_role(["survey.main.read", "survey.main.write"]) def test_roles(): return "Welcome to the Role endpoint!" with app.app_context(): yield app
def create_app(): # Define the WSGI application object application = Flask(__name__) add_blueprints(application) application.config["SESSION_COOKIE_SECURE"] = os.getenv( "SESSION_COOKIE_SECURE", False) application.secret_key = "my-secret-key" redis_address = os.getenv("REDIS_ADDRESS") if redis_address: set_redis_session(application, redis_address) auth_config = AuthConfig.from_env() oauth_client = new_oauth_client(auth_config) application.auth = Auth(auth_config, oauth_client, session) # Run with proxyfix when behind ELB as SSL is done at the load balancer if application.config["SESSION_COOKIE_SECURE"]: return ProxyFix(application, x_for=1, x_host=1) return application
def create_app(): app = Flask(__name__) app.config.update( DEBUG=True, SECRET_KEY='supersecret', DATABASE={ 'name': 'example.db', 'engine': 'peewee.SqliteDatabase', }, ) app.db = Database(app) Feedloggr(app, app.db) # OPTIONALLY SETUP BEGINS # Simple authentication for the admin interface app.auth = Auth(app, app.db) app.auth.User.create_table(fail_silently=True) # Try to create a new admin user, but fail silently if it already exists try: user = app.auth.User.create( username='******', email='.', password='', admin=True, active=True, ) except PIE: pass else: user.set_password('admin') user.save() # Initialize the admin interface app.admin = Admin(app, app.auth) app.auth.register_admin(app.admin) # Register the feedloggr feeds model app.admin.register(feedloggr_Feeds, feedloggr_FeedsAdmin) app.admin.setup() # OPTIONALLY SETUP ENDS return app
def create_app(database_credentials): """Creates a flask application. :param database_credentials: the database credentials. :return: the app """ app = Flask(__name__) from yetiserver.database import connect_to_database app.db = connect_to_database(database_credentials) from yetiserver.authentication import auth_manager_from_redis_connection app.auth = auth_manager_from_redis_connection(app.db) from yetiserver.model import model_manager_from_redis_conn app.model = model_manager_from_redis_conn(app.db) from yetiserver.model_log import model_log_from_redis_conn app.model_log = model_log_from_redis_conn(app.db) from yetiserver.api.v1 import register_api_blueprints register_api_blueprints(app) return app
def create_test_app(**kwargs): app = Flask(__name__) app.config["AZURE_OAUTH_TENANCY"] = config["AZURE_OAUTH_TENANCY"] app.config["AZURE_OAUTH_APPLICATION_ID"] = config[ "AZURE_OAUTH_APPLICATION_ID"] app.config["AZURE_OAUTH_CLIENT_APPLICATION_IDS"] = config[ "AZURE_OAUTH_CLIENT_APPLICATION_IDS"] app.config["TEST_JWKS"] = config["TEST_JWKS"] app.auth = TestFlaskAzureOauth( azure_tenancy_id=app.config["AZURE_OAUTH_TENANCY"], azure_application_id=app.config["AZURE_OAUTH_APPLICATION_ID"], azure_client_application_ids=app. config["AZURE_OAUTH_CLIENT_APPLICATION_IDS"], azure_jwks=app.config["TEST_JWKS"].jwks(), ) # Support invalid ways of setting up the auth provider when testing if "AUTH_MODE" in kwargs: if kwargs["AUTH_MODE"] == "null-jwks": app.auth.use_null_jwks() elif kwargs["AUTH_MODE"] == "broken-jwks": app.auth.use_broken_jwks() elif kwargs["AUTH_MODE"] == "replaced-jwks": app.auth.use_replaced_jwks() elif kwargs["AUTH_MODE"] == "restored-jwks": app.auth.use_restored_jwks() @app.route("/meta/auth/introspection") @app.auth() def meta_auth_introspection(): authorization_header = request.headers.get("authorization") token_string = authorization_header.split("Bearer ")[1] payload = { "data": { "token": app.auth.introspect_token(token_string=token_string), "token-rfc7662": app.auth.introspect_token_rfc7662(token_string=token_string), "token-string": token_string, } } return jsonify(payload) @app.route("/meta/auth/insufficient-scopes") @app.auth("unobtainable-scope") def meta_auth_insufficient_scopes(): """ Simulates a resource a client doesn't have access to due to not having the correct scopes. In practice it is impossible to access this resource. """ return "", HTTPStatus.NO_CONTENT @app.route("/meta/auth/sufficient-scope") @app.auth("scope") def meta_auth_sufficient_scope(): """ Simulates a resource a client has access to by having the correct scope. """ return "", HTTPStatus.NO_CONTENT @app.route("/meta/auth/sufficient-scopes") @app.auth("scope1 scope2") def meta_auth_sufficient_scopes(): """ Simulates a resource a client has access to by having the correct scopes. """ return "", HTTPStatus.NO_CONTENT return app
from app.auth import auth from cassandra.auth import PlainTextAuthProvider from cassandra.cluster import Cluster from cassandra.cqlengine import connection, models from flask import Flask import app.index.routes as index import app.sensors.routes as sensors import app.statistic.routes as statistic import app.token.routes as token import app.users.routes as users from config import Config # Setup app app = Flask(__name__) app.auth = auth app.config.from_object(Config) app.cassandra_auth_provider = PlainTextAuthProvider(username=app.config['CASSANDRA_USERNAME'], password=app.config['CASSANDRA_PASSWORD']) app.cluster = Cluster([app.config['CASSANDRA_CLUSTER_HOST']], auth_provider=app.cassandra_auth_provider) app.session = app.cluster.connect() app.session.set_keyspace('kaspa') connection.register_connection('clusterKaspa', session=app.session) connection.set_default_connection('clusterKaspa') models.DEFAULT_KEYSPACE = 'kaspa' app.register_blueprint(auth.mod)
from flask import Flask, render_template, request # from public_inventory import public_inventory from inventory import inventory from lib import Authentificator, required_roles # Configure app app = Flask(__name__) babel = Babel(app) app.config.update(LANGUAGES=['en', 'fr', 'de']) # app.register_blueprint(public_inventory, url_prefix='/public_inventory') app.register_blueprint(inventory, url_prefix='/inventory') app.secret_key = 'dummy1' app.auth = Authentificator() @babel.localeselector def get_locale(): if request.args.get('lang', None): return request.args.get('lang') if request.form.get('lang', None): return request.form['lang'] if request.headers.get('Accept-Language'): langs = request.headers.get('Accept-Language').split(',') if len(langs) > 0 and 'fr' in langs[0]: if 'fr' in langs[0]: return 'fr' if 'de' in langs[0]: return 'de'
def login(): if request.method == 'POST': if valid_login(): session['username'] = request.form['username'] referee = request.args.get('from', '') if referee != '': return redirect(referee) return "login ok" else: abort(403) else: return render_template('login.html') @app.route("/logout") def logout(): if 'username' in session: session.pop('username', None) return "logout" if __name__ == "__main__": with open('auth.json') as auth_file: app.auth = json.load(auth_file) app.run()
from flask import Flask, jsonify from oauth1.authorize import Oauth1 from oauth1.errors.oauth import Oauth1Errors from oauth1.store.nosql import Oauth1StoreRedis from oauth1.store.base import Oauth1StoreBase BASE_URL = "http://*****:*****@127.0.0.1:3306/oauth" # Change this to a valid URI app.auth = None app.config['REDIS_HOST'] = '127.0.0.1' app.config['REDIS_PORT'] = 6379 app.config['REDIS_DB'] = 0 app.config['REDIS_NS'] = 'oauth1-provider-nosql' class RedisProvider(Oauth1): def __init__(self): store = Oauth1StoreRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT'], db=app.config['REDIS_DB'], namespace=app.config['REDIS_NS']) super(RedisProvider, self).__init__(base_url=BASE_URL, store=store) def _verify_xauth_credentials(self, username, password): return username == 'username' and password == 'password' @app.before_first_request
from functools import wraps from flask import (g, request, Response, Flask, jsonify) from flask.ext.httpauth import HTTPBasicAuth from models.base import db from services.cyclopedia_service import CyclopediaService from services.user_service import UserService from services.entry_service import EntryService from services.authentication_service import AuthenticationService from presenters.user_presenter import UserPresenter from presenters.cyclopedia_presenter import CyclopediaPresenter from presenters.entry_presenter import EntryPresenter app = Flask(__name__) app.config.from_object('config.DevelopmentConfig') app.auth = HTTPBasicAuth() db.init_app(app) def authenticate(): """Sends a 401 response that enables basic auth""" return Response('Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'}) def require_apikey(fn): @wraps(fn) def _wrap(*args, **kwargs): auth = request.authorization if not auth:
from flask import Flask, jsonify from oauth1.authorize import Oauth1 from oauth1.errors.oauth import Oauth1Errors from oauth1.store.sql import Oauth1StoreSQLAlchemy BASE_URL = "http://*****:*****@127.0.0.1:3306/oauth" # Change this to a valid URI app.auth = None class SQLProvider(Oauth1): def __init__(self): store = Oauth1StoreSQLAlchemy(app=app) super(SQLProvider, self).__init__(base_url=BASE_URL, store=store) def _verify_xauth_credentials(self, username, password): return username == 'username' and password == 'password' @app.before_first_request def after_run(): global app app.auth = SQLProvider() oauth_app = app.auth.store.create_new_consumer_app(app_name='Test App %d' % Oauth1StoreSQLAlchemy.get_unix_time(), app_desc='Just Testing', app_platform='CLI', app_url=BASE_URL) print "OAuth App:", oauth_app tokens = app.auth.store.create_new_consumer_tokens(app_id=oauth_app['app_id'])
def create_app(): app = Flask(__name__) app.config["SECRET_KEY"] = "TPZHP2Ljw82CSXR5BjjfoQ" ## Note: If changing between config sets, make sure to update required scopes in routes as well ## Config options for 'Flask Azure OAuth Provider - Example App 1' (version 1.0 tokens) # app.config["AZURE_OAUTH_TENANCY"] = "d14c529b-5558-4a80-93b6-7655681e55d6" # app.config["AZURE_OAUTH_APPLICATION_ID"] = "be76d0cc-26ab-4c07-8bae-ed544224078f" # app.config["AZURE_OAUTH_CLIENT_APPLICATION_IDS"] = ["da553d65-9dca-4393-a604-875addd10f13"] # app.config["AUTH_CLIENT_ID"] = "da553d65-9dca-4393-a604-875addd10f13" # app.config["AUTH_CLIENT_TENANCY"] = "https://login.microsoftonline.com/d14c529b-5558-4a80-93b6-7655681e55d6" # app.config["AUTH_CLIENT_SCOPES"] = [ # "api://be76d0cc-26ab-4c07-8bae-ed544224078f/BAS.WSF.FlaskOAuthProvider.Examples.Example1.Access" # ] ## Config options for 'Flask Azure OAuth Provider - Example App 2' (version 2.0 tokens) app.config["AZURE_OAUTH_TENANCY"] = "d14c529b-5558-4a80-93b6-7655681e55d6" app.config[ "AZURE_OAUTH_APPLICATION_ID"] = "de40e653-e63b-46e3-80f6-52a39f055bf3" app.config["AZURE_OAUTH_CLIENT_APPLICATION_IDS"] = [ "c5134fdc-f69a-4b80-ad55-66c4d6e5a2b0" ] app.config["AUTH_CLIENT_ID"] = "c5134fdc-f69a-4b80-ad55-66c4d6e5a2b0" app.config["AUTH_CLIENT_SECRET"] = "yq__4pGnY4RQ.Z3w~g_~ZFBF09S_07ergR" app.config[ "AUTH_CLIENT_TENANCY"] = "https://login.microsoftonline.com/d14c529b-5558-4a80-93b6-7655681e55d6" app.config["AUTH_CLIENT_SCOPES"] = [ "api://de40e653-e63b-46e3-80f6-52a39f055bf3/BAS.WSF.FlaskOAuthProvider.Examples.Example2.Access" ] app.auth = FlaskAzureOauth() app.auth.init_app(app) @app.route("/auth/sign-in") def auth_sign_in(): session["state"] = str(uuid4()) auth_url = ConfidentialClientApplication( app.config["AUTH_CLIENT_ID"], authority=current_app.config["AUTH_CLIENT_TENANCY"], client_credential=app.config["AUTH_CLIENT_SECRET"], ).get_authorization_request_url( scopes=current_app.config["AUTH_CLIENT_SCOPES"], state=session.get("state"), redirect_uri="http://*****:*****@app.route("/auth/callback") def auth_callback(): if request.args.get("state") != session.get("state"): return "Sign-in failed, state doesn't match.", 403 if request.args.get("error"): return request.args.get("error"), 403 if not request.args.get("code"): return "Sign-in failed, no auth code.", 403 result = ConfidentialClientApplication( app.config["AUTH_CLIENT_ID"], authority=current_app.config["AUTH_CLIENT_TENANCY"], client_credential=app.config["AUTH_CLIENT_SECRET"], ).acquire_token_by_authorization_code( code=request.args.get("code"), scopes=current_app.config["AUTH_CLIENT_SCOPES"], redirect_uri="http://*****:*****@app.route("/unprotected") def unprotected(): return "Unprotected resource." @app.route("/protected") @app.auth() def protected(): return "Protected resource." @app.route("/protected-with-single-scope") # @app.auth("BAS.WSF.FlaskOAuthProvider.Examples.Example1.Scope1") @app.auth("BAS.WSF.FlaskOAuthProvider.Examples.Example2.Scope1") def protected_with_scope(): return "Protected resource requiring single scope." @app.route("/protected-with-multiple-scopes") # @app.auth("BAS.WSF.FlaskOAuthProvider.Examples.Example1.Scope1 BAS.WSF.FlaskOAuthProvider.Examples.Example1.Scope2") @app.auth( "BAS.WSF.FlaskOAuthProvider.Examples.Example2.Scope1 BAS.WSF.FlaskOAuthProvider.Examples.Example2.Scope2" ) def protected_with_multiple_scopes(): return "Protected resource requiring multiple scopes." @app.cli.command("access-resource") @click.argument( "resource", type=click.Choice([ "unprotected", "protected", "protected-with-single-scope", "protected-with-multiple-scopes" ]), ) @click.option("-t", "--access-token") def access_resource(resource, access_token): """Simulates a user requesting a resource""" if access_token is not None: current_app.config["AUTH_TOKEN"] = access_token if resource != "unprotected" and "AUTH_TOKEN" not in current_app.config: _get_token() client_headers = {} if "AUTH_TOKEN" in current_app.config: client_headers[ "Authorization"] = f"Bearer {current_app.config['AUTH_TOKEN']}" client = current_app.test_client() response = client.get(f"/{resource}", headers=client_headers) click.echo(f"Response status code: {response.status_code}") click.echo(f"Response data: {response.data.decode()}") def _get_token(): auth_client = PublicClientApplication( client_id=current_app.config["AUTH_CLIENT_ID"], authority=current_app.config["AUTH_CLIENT_TENANCY"]) auth_flow = auth_client.initiate_device_flow( scopes=current_app.config["AUTH_CLIENT_SCOPES"]) click.pause( f"To sign-in, visit 'https://microsoft.com/devicelogin', enter this code '{auth_flow['user_code']}' and then press any key..." ) auth_payload = auth_client.acquire_token_by_device_flow(auth_flow) current_app.config["AUTH_TOKEN"] = auth_payload["access_token"] click.echo(current_app.config["AUTH_TOKEN"]) click.echo(f"Ok. Access token set.") return app
import config from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from finance.utils import Auth app = Flask(__name__) app.config.from_object(config) app.auth = Auth() db = SQLAlchemy(app) import finance.views.base # noqa
import optparse from flask import Flask from flask_httpauth import HTTPBasicAuth flask_app = Flask(__name__) flask_app.auth = HTTPBasicAuth() with flask_app.app_context(): from apis.routing import setup_api_routing setup_api_routing() if __name__ == '__main__': # Set up the command-line options default_host, default_port, debug_mode = '0.0.0.0', 5051, True parser = optparse.OptionParser() parser.add_option( "-H", "--host", help="Host of the Flask-app default: {host}".format(host=default_host), default=default_host ) parser.add_option( "-P", "--port", help="Port for the Flask-app default: {port}".format(port=default_port), default=default_port ) parser.add_option( "--nd", "--nodebug",
def create_app(**kwargs): app = Flask(__name__) app.config["AZURE_OAUTH_TENANCY"] = "test" app.config["AZURE_OAUTH_APPLICATION_ID"] = "test" app.config["AZURE_OAUTH_CLIENT_APPLICATION_IDS"] = ["test", "test2"] app.config["TEST_JWKS"] = test_jwks # Support using session app.config["SECRET_KEY"] = "5c7KjhU3dm4ZPz6BevZ2xw" # Support overriding auth provider config when testing if "AZURE_OAUTH_TENANCY" in kwargs: app.config["AZURE_OAUTH_TENANCY"] = kwargs["AZURE_OAUTH_TENANCY"] if "AZURE_OAUTH_APPLICATION_ID" in kwargs: app.config["AZURE_OAUTH_APPLICATION_ID"] = kwargs[ "AZURE_OAUTH_APPLICATION_ID"] if "AZURE_OAUTH_CLIENT_APPLICATION_IDS" in kwargs: app.config["AZURE_OAUTH_CLIENT_APPLICATION_IDS"] = kwargs[ "AZURE_OAUTH_CLIENT_APPLICATION_IDS"] with patch.object(FlaskAzureOauth, "_get_jwks") as mocked_get_jwks: mocked_get_jwks.side_effect = _get_jwks app.auth = TestFlaskAzureOauth() app.auth.init_app(app) # Support invalid ways of setting up the auth provider when testing if "AUTH_MODE" in kwargs: if kwargs["AUTH_MODE"] == "null-jwks": app.auth.use_null_jwks() elif kwargs["AUTH_MODE"] == "broken-jwks": app.auth.use_broken_jwks() elif kwargs["AUTH_MODE"] == "replaced-jwks": app.auth.use_replaced_jwks() elif kwargs["AUTH_MODE"] == "restored-jwks": app.auth.use_restored_jwks() @app.route("/meta/auth/introspection") @app.auth() def meta_auth_introspection(): authorization_header = request.headers.get("authorization") if authorization_header is None: authorization_header = f"Bearer {session['access_token']}" token_string = authorization_header.split("Bearer ")[1] payload = { "data": { "token": app.auth.introspect_token(token_string=token_string), "token-rfc7662": app.auth.introspect_token_rfc7662(token_string=token_string), "token-string": token_string, } } return jsonify(payload) @app.route("/meta/auth/insufficient-scopes") @app.auth("unobtainable-scope") def meta_auth_insufficient_scopes(): """ Simulates a resource a client doesn't have access to due to not having the correct scopes. In practice it is impossible to access this resource. """ return "", HTTPStatus.NO_CONTENT @app.route("/meta/auth/sufficient-scope") @app.auth("scope") def meta_auth_sufficient_scope(): """ Simulates a resource a client has access to by having the correct scope. """ return "", HTTPStatus.NO_CONTENT @app.route("/meta/auth/sufficient-scopes") @app.auth("scope1 scope2") def meta_auth_sufficient_scopes(): """ Simulates a resource a client has access to by having the correct scopes. """ return "", HTTPStatus.NO_CONTENT return app