def init_app(self, provider_metadata_extras=None, client_metadata_extras=None, **kwargs): required_provider_metadata = { "issuer": self.PROVIDER_BASEURL, "authorization_endpoint": self.PROVIDER_BASEURL + "/auth", "jwks_uri": self.PROVIDER_BASEURL + "/jwks", } if provider_metadata_extras: required_provider_metadata.update(provider_metadata_extras) provider_metadata = ProviderMetadata(**required_provider_metadata) required_client_metadata = { "client_id": self.CLIENT_ID, "client_secret": "secret1" } if client_metadata_extras: required_client_metadata.update(client_metadata_extras) client_metadata = ClientMetadata(**required_client_metadata) provider_configurations = { self.PROVIDER_NAME: ProviderConfiguration(provider_metadata=provider_metadata, client_metadata=client_metadata, **kwargs) } authn = OIDCAuthentication(provider_configurations) authn.init_app(self.app) return authn
def init_app(self, provider_metadata_extras=None, client_metadata_extras=None, **kwargs): required_provider_metadata = { 'issuer': self.PROVIDER_BASEURL, 'authorization_endpoint': self.PROVIDER_BASEURL + '/auth', 'jwks_uri': self.PROVIDER_BASEURL + '/jwks' } if provider_metadata_extras: required_provider_metadata.update(provider_metadata_extras) provider_metadata = ProviderMetadata(**required_provider_metadata) required_client_metadata = { 'client_id': self.CLIENT_ID, 'client_secret': 'secret1' } if client_metadata_extras: required_client_metadata.update(client_metadata_extras) client_metadata = ClientMetadata(**required_client_metadata) provider_configurations = { self.PROVIDER_NAME: ProviderConfiguration(provider_metadata=provider_metadata, client_metadata=client_metadata, **kwargs) } authn = OIDCAuthentication(provider_configurations) authn.init_app(self.app) return authn
def test_explicit_redirect_uri_config_should_be_preserved_after_init_app( self): redirect_uri_config = RedirectUriConfig( 'https://example.com/abc/redirect_uri', 'redirect_uri') authn = OIDCAuthentication({}, None, redirect_uri_config) assert authn._redirect_uri_config == redirect_uri_config authn.init_app(self.app) assert authn._redirect_uri_config == redirect_uri_config
def test_should_register_client_if_not_registered_before( self, post_logout_redirect_uris): registration_endpoint = self.PROVIDER_BASEURL + '/register' provider_metadata = ProviderMetadata( self.PROVIDER_BASEURL, self.PROVIDER_BASEURL + '/auth', self.PROVIDER_BASEURL + '/jwks', registration_endpoint=registration_endpoint) client_metadata = {} if post_logout_redirect_uris: client_metadata[ 'post_logout_redirect_uris'] = post_logout_redirect_uris provider_configurations = { self.PROVIDER_NAME: ProviderConfiguration( provider_metadata=provider_metadata, client_registration_info=ClientRegistrationInfo( **client_metadata)) } authn = OIDCAuthentication(provider_configurations) authn.init_app(self.app) # register logout view to force 'post_logout_redirect_uris' to be included in registration request logout_view_mock = self.get_view_mock() self.app.add_url_rule('/logout', view_func=logout_view_mock) authn.oidc_logout(logout_view_mock) responses.add(responses.POST, registration_endpoint, json={ 'client_id': 'client1', 'client_secret': 'secret1' }) view_mock = self.get_view_mock() with self.app.test_request_context('/'): auth_redirect = authn.oidc_auth(self.PROVIDER_NAME)(view_mock)() self.assert_auth_redirect(auth_redirect) registration_request = json.loads( responses.calls[0].request.body.decode('utf-8')) with self.app.app_context(): full_redirect_uri = flask.url_for( registration_request['redirect_uris'][0]) registration_request['redirect_uris'] = full_redirect_uri expected_post_logout_redirect_uris = post_logout_redirect_uris if post_logout_redirect_uris else [ 'http://{}/logout'.format(self.CLIENT_DOMAIN) ] expected_registration_request = { 'redirect_uris': 'http://{}/redirect_uri'.format(self.CLIENT_DOMAIN), 'post_logout_redirect_uris': expected_post_logout_redirect_uris } assert registration_request == expected_registration_request
def test_explicit_redirect_uri_config_should_be_preferred(self): redirect_uri_config = RedirectUriConfig( 'https://example.com/abc/redirect_uri', 'redirect_uri') assert OIDCAuthentication( {}, self.app, redirect_uri_config)._redirect_uri_config == redirect_uri_config
# Flask web framework configuration # See http://flask.pocoo.org/docs/0.12/config/ app.config.update({ 'SECRET_KEY': 'flask_session_key', # make sure to change this!! 'JSONIFY_PRETTYPRINT_REGULAR': True, 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(minutes=1).total_seconds(), }) auth_provider_config = ProviderConfiguration(issuer=AUTH_PROVIDER_BASE_URI, client_metadata=ClientMetadata( APP_CLIENT_ID, APP_SECRET)) auth = OIDCAuthentication({AUTH_PROVIDER_NAME: auth_provider_config}) def get_my_groups(user_session): headers = {"Authorization": f"Bearer {user_session.access_token}"} response = requests.get(GROUPS_BASE_URI + '/' + MY_GROUPS_PATH, headers=headers) response.raise_for_status() return response.json() @app.route('/') @auth.oidc_auth(AUTH_PROVIDER_NAME) def login1(): user_session = UserSession(flask.session) mygroups = get_my_groups(user_session)
"GPM_OIDC_INTROSPECTION_ENDPOINT"), userinfo_endpoint=os.environ.get("GPM_OIDC_USERINFO_ENDPOINT"), end_session_endpoint=os.environ.get("GPM_OIDC_END_SESSION_ENDPOINT"), ) provider_config = ProviderConfiguration( issuer=os.environ.get("GPM_OIDC_ISSUER"), provider_metadata=provider_metadata, session_refresh_interval_seconds=10, client_metadata=ClientMetadata( client_id=os.environ.get("GPM_OIDC_CLIENT_ID"), client_secret=os.environ.get("GPM_OIDC_CLIENT_SECRET"), ), ) auth = OIDCAuthentication({"oidc": provider_config}, app) else: app.logger.info("RUNNING WITH AUTHENTICATION DISABLED") # This snippet tries to detect if the app is running on a K8S cluster or locally try: app.logger.info("Attempting init with KUBECONFIG") config.load_kube_config() app.logger.info( f"KUBECONFIG '{config.kube_config.KUBE_CONFIG_DEFAULT_LOCATION}' successfuly loaded." ) app.config["MODE"] = "KUBECONFIG" except config.ConfigException as e: if app.config.get("KUBERNETES"): app.logger.debug(f"KUBECONFIG loading failed. Got error: {e}") app.logger.info(
True, 'SESSION_TYPE': 'filesystem', 'SESSION_FILE_DIR': '/tmp/sessions' }) app.config['OIDC_PROVIDERS'] = 'provider1' app.config['provider1_ISSUER'] = '<auth base url>' app.config['provider1_CLIENT'] = '<client id>' app.config['provider1_SECRET'] = '' app.config['OIDC_REQUIRED_ROLES'] = "admin" app.config['OIDC_ROLE_CLAIM'] = "realm_access.roles" Session(app) auth = OIDCAuthentication(app=app) @app.route('/') @auth.oidc_auth(bearer=True) def login1(): user_session = UserSession(flask.session) return jsonify(access_token=user_session.access_token, id_token=user_session.id_token, userinfo=user_session.userinfo) @app.route('/bearer_test') @auth.oidc_auth() def bearer_test(): user_session = UserSession(flask.session)
'PREFERRED_URL_SCHEME': 'http', 'DEBUG': True, 'SQLALCHEMY_DATABASE_URI': 'sqlite:///test.db' }) # app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' db = SQLAlchemy(app) ISSUER1 = 'http://*****:*****@app.route('/', methods=['POST', 'GET']) # @auth.oidc_auth(PROVIDER_NAME1) def index(): # user_session = UserSession(flask.session)
SECRET_KEY=''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(16)), SERVER_NAME=f'{socket.getfqdn()}:5000', JSONIFY_PRETTYPRINT_REGULAR=True, ) provider_config = ProviderConfiguration( auth_request_params={'scope': openid_config['scope']}, issuer=openid_config['issuer'], client_metadata=ClientMetadata( client_id=openid_config['client_id'], client_secret=openid_config['client_secret'], )) auth = OIDCAuthentication({'default': provider_config}, app) @app.route('/') @auth.oidc_auth('default') def login(): user_session = UserSession(flask.session, provider_name='default').userinfo print(user_session) return jsonify(user_session) @app.route('/logout') @auth.oidc_logout def logout(): return 'logged out'
os.environ.get('REDIRECT_URI'), 'SECRET_KEY': os.environ.get('SECRET'), 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(days=7).total_seconds(), 'DEBUG': True }) provider_config = ProviderConfiguration( issuer=os.environ.get('OAUTH_SERVER_URL'), client_metadata=ClientMetadata(os.environ.get('CLIENT_ID'), os.environ.get('SECRET'))) PROVIDER = 'provider' auth = OIDCAuthentication({PROVIDER: provider_config}, app) @app.route('/') @app.route('/index') def index(): return render_template('index.html', title='Home') @app.route('/login') @auth.oidc_auth(PROVIDER) def login(): user_session = UserSession(flask.session) user_data = { 'access_token': user_session.access_token, 'id_token': user_session.id_token,
issuer = f'https://{app.config["PROVIDER_NAME"]}' cognito_config = ProviderConfiguration( provider_metadata=ProviderMetadata( issuer=issuer, authorization_endpoint=f'{app.config["COGNITO_URL"]}/oauth2/authorize', jwks_uri=f'{issuer}/.well-known/jwks.json', token_endpoint=f'{app.config["COGNITO_URL"]}/oauth2/token', ), client_metadata=ClientMetadata(app.config["CLIENT_ID"], app.config["CLIENT_SECRET"]), auth_request_params={ 'scope': ['openid', 'aws.cognito.signin.user.admin' ] # scope required to update MFA for logged-in user }) auth = OIDCAuthentication({'cognito': cognito_config}) aws_accesser = AwsAccesser(app.config['AWS_ACCOUNT_ID'], app.config['IDENTITY_POOL_ID'], app.config['PROVIDER_NAME']) @app.route('/') @auth.oidc_auth('cognito') def index(): user_session = UserSession(flask.session) if not user_has_software_token_mfa(user_session.access_token): challenge = get_mfa_challenge(user_session.access_token) flask.session['mfa-challenge'] = challenge return redirect(url_for('verify_mfa'), code=303)
token_endpoint=os.environ.get('GPM_OIDC_TOKEN_ENDPOINT'), token_introspection_endpoint=os.environ.get( 'GPM_OIDC_INTROSPECTION_ENDPOINT'), userinfo_endpoint=os.environ.get('GPM_OIDC_USERINFO_ENDPOINT'), end_session_endpoint=os.environ.get('GPM_OIDC_END_SESSION_ENDPOINT'), ) provider_config = ProviderConfiguration( issuer=os.environ.get('GPM_OIDC_ISSUER'), provider_metadata=provider_metadata, session_refresh_interval_seconds=10, client_metadata=ClientMetadata( client_id=os.environ.get('GPM_OIDC_CLIENT_ID'), client_secret=os.environ.get('GPM_OIDC_CLIENT_SECRET'))) auth = OIDCAuthentication({'oidc': provider_config}, app) else: app.logger.info('RUNNING WITH AUTHENTICATION DISABLED') def dict_to_li(my_dict, html): """Recursive function to convert dict items into <li> html tags""" if my_dict is None: return html for k, v in my_dict.items(): app.logger.debug("Processing %s, %s" % (k, v)) if not isinstance(v, dict): html += '<li>%s: %s</li>' % (k, v) else: html += '<li>%s: %s</li>' % (k, dict_to_li(v, html)) html += "</ul>"
def test_unauth_error(self): with pytest.raises(NoAuthenticationError) as excinfo: authn = OIDCAuthentication() authn.init_app(self.app)
}) ISSUER1 = 'https://provider1.example.com' CLIENT1 = 'client@provider1' PROVIDER_NAME1 = 'provider1' PROVIDER_CONFIG1 = ProviderConfiguration(issuer=ISSUER1, client_metadata=ClientMetadata( CLIENT1, 'secret1')) ISSUER2 = 'https://provider2.example.com' CLIENT2 = 'client@provider2' PROVIDER_NAME2 = 'provider2' PROVIDER_CONFIG2 = ProviderConfiguration(issuer=ISSUER2, client_metadata=ClientMetadata( CLIENT2, 'secret2')) auth = OIDCAuthentication({ PROVIDER_NAME1: PROVIDER_CONFIG1, PROVIDER_NAME2: PROVIDER_CONFIG2 }) @app.route('/') @auth.oidc_auth(PROVIDER_NAME1) def login1(): user_session = UserSession(flask.session) return jsonify(access_token=user_session.access_token, id_token=user_session.id_token, userinfo=user_session.userinfo) @app.route('/login2') @auth.oidc_auth(PROVIDER_NAME2) def login2():
load_dotenv() app = Flask(__name__) app.config.update( OIDC_REDIRECT_URI = 'http://*****:*****@app.route('/login') @auth.oidc_auth('default') def login(): user_session = UserSession(session, 'default') return redirect('/') @app.route('/logout') @auth.oidc_logout def logout(): return redirect('/') @auth.error_view def error(error=None, error_description=None): return jsonify({'error': error, 'message': error_description})
from flask_pyoidc.provider_configuration import ProviderConfiguration, ClientMetadata from flask_pyoidc.user_session import UserSession app = Flask(__name__) # See http://flask.pocoo.org/docs/0.12/config/ app.config.update({"OIDC_REDIRECT_URI": "http://*****:*****@app.route("/") @auth.oidc_auth(PROVIDER_NAME) def login(): user_session = UserSession(flask.session) return jsonify(access_token=user_session.access_token, id_token=user_session.id_token, userinfo=user_session.userinfo) @app.route("/logout") @auth.oidc_logout def logout(): return "You've been successfully logged out!"
provider_data = json.load(provider_file) for provider in provider_data: config = ProviderConfiguration( issuer=provider_data[provider]['issuer'], client_metadata=ClientMetadata( provider_data[provider]['client_id'], provider_data[provider]['client_secret'], post_logout_redirect_uris=[logout_uri + '/logout'])) oidc_config.update({provider: config}) return oidc_config base_uri = os.environ.get("BASE_URI") if not base_uri: raise ValueError("No BASE_URI environment set for application") auth = OIDCAuthentication(parse_oidc_config(base_uri)) bootstrap = Bootstrap() def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) bootstrap.init_app(app) auth.init_app(app) # init blueprints from app.errors import bp as errors_bp app.register_blueprint(errors_bp)
'text/html', 'text/css', 'text/plain', 'text/csv', 'text/turtle', 'application/json', 'application/javascript', 'application/trig' ], ) app.json_encoder = FixedJSONEncoder app.url_map.converters['job'] = JobConverter app.url_map.converters['type'] = TypeConverter CORS(app) auth = OIDCAuthentication( { 'default': ProviderConfiguration( issuer=os.environ['OIDC_SERVER'], client_metadata=ClientMetadata( client_id=os.environ['OIDC_CLIENT_ID'], client_secret=os.environ['OIDC_CLIENT_SECRET']), auth_request_params={'scope': ['openid', 'email', 'profile']}, ) }, app) if 'OIDC_SERVER' in os.environ and len( os.environ['OIDC_SERVER']) > 0 else None socketio = SocketIO(app, cors_allowed_origins='*') socketio.start_background_task(emit_database_events) def authenticated(func): @functools.wraps(func) def wrapper(*args, **kwargs): if auth: