oidc working again (getting less info to limit cookie size)

This commit is contained in:
Tobias Kurze
2020-07-28 15:09:08 +02:00
parent de398d189a
commit cc334f1727
8 changed files with 40 additions and 18 deletions

View File

@@ -3,6 +3,7 @@
Backend base module Backend base module
""" """
import logging import logging
import os
from io import StringIO from io import StringIO
from logging.config import dictConfig from logging.config import dictConfig
from logging.handlers import MemoryHandler from logging.handlers import MemoryHandler
@@ -120,6 +121,9 @@ class LrcException(Exception):
app = Flask(__name__) app = Flask(__name__)
if os.environ.get('FLASK_ENV', None) == "development":
app.config.from_object('backend.config.DevelopmentConfig')
else:
app.config.from_object('backend.config.Config') app.config.from_object('backend.config.Config')
db = SQLAlchemy(app) db = SQLAlchemy(app)

View File

@@ -26,7 +26,6 @@ def _start_initial_recorder_state_update(run_in_thread=True):
async_permanent_cron_recorder_checker.check_object_state() # initial check of all recorders async_permanent_cron_recorder_checker.check_object_state() # initial check of all recorders
def _create_and_start_default_scheduler(): def _create_and_start_default_scheduler():
print("Starting Scheduler") print("Starting Scheduler")
scheduler = get_default_scheduler() scheduler = get_default_scheduler()
@@ -48,14 +47,23 @@ def main():
add_test_recorder() add_test_recorder()
print(app.config.get("SERVER_NAME", None)) print(app.config.get("SERVER_NAME", None))
server_name = app.config.get("SERVER_NAME", None)
if server_name is not None and "ubkaps154.ubka.uni-karlsruhe.de" in server_name: if app.config.get("USE_SSL", False):
try: try:
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.load_cert_chain('cert.pem', 'key.pem') context.load_cert_chain(app.config.get("CERT", 'cert.pem'), app.config.get("KEY", 'key.pem'))
app.run(debug=True, ssl_context=context, threaded=True) print("using ssl context!")
app.run(debug=True, ssl_context=context, threaded=True,
#host="0.0.0.0",
host=app.config.get("HOST", "0.0.0.0"),
port=app.config.get("PORT", 5443)
)
except FileNotFoundError: except FileNotFoundError:
app.run(debug=True, threaded=True) print("Could not find cert/key.pem!")
app.run(debug=True, threaded=True,
host=app.config.get("HOST", None),
port=app.config.get("PORT", 5443)
)
try: try:
db.create_all() db.create_all()

View File

@@ -28,6 +28,7 @@ from werkzeug.routing import BuildError
from backend import db, app, jwt_extended from backend import db, app, jwt_extended
from backend.api import auth_api_bp, auth_api_providers_ns, auth_api_register_ns from backend.api import auth_api_bp, auth_api_providers_ns, auth_api_register_ns
from backend.auth import AUTH_PROVIDERS, oidc_auth from backend.auth import AUTH_PROVIDERS, oidc_auth
from backend.auth.oidc_config import PROVIDER_NAME
from backend.models.user_model import User, Group, BlacklistToken from backend.models.user_model import User, Group, BlacklistToken
logger = logging.getLogger("lrc.api.auth") logger = logging.getLogger("lrc.api.auth")
@@ -133,6 +134,7 @@ def create_or_retrieve_user_from_userinfo(userinfo):
try: try:
email = userinfo["email"] email = userinfo["email"]
except KeyError: except KeyError:
logger.error("email is missing in OIDC userinfo! Can't create user!")
return None return None
user_groups = check_and_create_groups(groups=userinfo.get("memberOf", [])) user_groups = check_and_create_groups(groups=userinfo.get("memberOf", []))
@@ -161,13 +163,12 @@ def create_or_retrieve_user_from_userinfo(userinfo):
@auth_api_bp.route('/oidc', methods=['GET']) @auth_api_bp.route('/oidc', methods=['GET'])
@auth_api_bp.route('/oidc/<redirect_url>', methods=['GET']) @auth_api_bp.route('/oidc/<redirect_url>', methods=['GET'])
@oidc_auth.oidc_auth() @oidc_auth.oidc_auth(provider_name=PROVIDER_NAME)
def oidc(redirect_url=None): def oidc(redirect_url=None):
logger.debug("oidc auth endpoint:") logger.debug("oidc auth endpoint:")
return "fuck!"
user = create_or_retrieve_user_from_userinfo(flask.session['userinfo']) user = create_or_retrieve_user_from_userinfo(flask.session['userinfo'])
if user is None: if user is None:
logger.error("Could not authenticate: could not find or create user.") logger.error(f"Could not authenticate: could not find or create user:\n{str(flask.session['userinfo'])}")
return "Could not authenticate: could not find or create user.", 401 return "Could not authenticate: could not find or create user.", 401
if current_app.config.get("AUTH_RETURN_EXTERNAL_JWT", False): if current_app.config.get("AUTH_RETURN_EXTERNAL_JWT", False):
token = jwt.encode(flask.session['id_token'], current_app.config['SECRET_KEY']) token = jwt.encode(flask.session['id_token'], current_app.config['SECRET_KEY'])

View File

@@ -18,7 +18,7 @@ from .oidc_config import PROVIDER_NAME, OIDC_PROVIDERS
OIDCAuthentication.oidc_auth_orig = OIDCAuthentication.oidc_auth OIDCAuthentication.oidc_auth_orig = OIDCAuthentication.oidc_auth
OIDCAuthentication.oidc_logout_orig = OIDCAuthentication.oidc_logout OIDCAuthentication.oidc_logout_orig = OIDCAuthentication.oidc_logout
'''
def oidc_auth_default_provider(self): def oidc_auth_default_provider(self):
"""monkey patch oidc_auth""" """monkey patch oidc_auth"""
return self.oidc_auth_orig(PROVIDER_NAME) return self.oidc_auth_orig(PROVIDER_NAME)
@@ -31,6 +31,7 @@ def oidc_logout_default_provider(self):
OIDCAuthentication.oidc_auth = oidc_auth_default_provider OIDCAuthentication.oidc_auth = oidc_auth_default_provider
OIDCAuthentication.oidc_logout = oidc_logout_default_provider OIDCAuthentication.oidc_logout = oidc_logout_default_provider
'''
oidc_auth = OIDCAuthentication(OIDC_PROVIDERS) oidc_auth = OIDCAuthentication(OIDC_PROVIDERS)
@@ -40,6 +41,7 @@ def create_or_retrieve_user_from_userinfo(userinfo):
try: try:
email = userinfo["email"] email = userinfo["email"]
except KeyError: except KeyError:
app.logger.error("email is missing in OIDC userinfo! Can't create user!")
return None return None
user = User.get_by_identifier(email) user = User.get_by_identifier(email)
@@ -62,7 +64,7 @@ def create_or_retrieve_user_from_userinfo(userinfo):
@auth_bp.route('/oidc', methods=['GET']) @auth_bp.route('/oidc', methods=['GET'])
@oidc_auth.oidc_auth() @oidc_auth.oidc_auth(provider_name=PROVIDER_NAME)
def oidc(): def oidc():
user_session = UserSession(flask.session) user_session = UserSession(flask.session)
app.logger.info(user_session.userinfo) app.logger.info(user_session.userinfo)
@@ -78,8 +80,10 @@ def oidc():
@auth_bp.route('/oidc_logout', methods=['GET']) @auth_bp.route('/oidc_logout', methods=['GET'])
@oidc_auth.oidc_logout
def oidc_logout(): def oidc_logout():
oidc_auth.oidc_logout() # oidc_auth.oidc_logout()
app.logger.debug("Logging out current user!")
return redirect('/') return redirect('/')

View File

@@ -10,6 +10,10 @@ PROVIDER_URL = "https://oidc.scc.kit.edu/auth/realms/kit"
PROVIDER_NAME = 'kit_oidc' PROVIDER_NAME = 'kit_oidc'
PROVIDER_CONFIG = ProviderConfiguration(issuer=PROVIDER_URL, PROVIDER_CONFIG = ProviderConfiguration(issuer=PROVIDER_URL,
client_metadata=CLIENT_METADATA, client_metadata=CLIENT_METADATA,
auth_request_params={'scope': ['openid', 'email', 'profile']}) auth_request_params={'scope': ['openid', 'email']}
# auth_request_params={'scope': ['openid', 'profile']} # avoid to get profile
# -> cookie is getting too large
# auth_request_params={'scope': ['openid', 'email', 'profile']}
)
OIDC_PROVIDERS = {PROVIDER_NAME: PROVIDER_CONFIG} OIDC_PROVIDERS = {PROVIDER_NAME: PROVIDER_CONFIG}

Binary file not shown.

View File

@@ -170,6 +170,6 @@ async_cron_recorder_checker = StateChecker([check_capture_agent_state, ping_capt
async_permanent_cron_recorder_checker = StateChecker( async_permanent_cron_recorder_checker = StateChecker(
[check_capture_agent_state, ping_capture_agent, check_stream_sanity], Recorder) [check_capture_agent_state, ping_capture_agent, check_stream_sanity], Recorder)
for r in Recorder.get_all(): #for r in Recorder.get_all():
async_permanent_cron_recorder_checker.add_object_to_state_check(r.id) # async_permanent_cron_recorder_checker.add_object_to_state_check(r.id)

View File

@@ -10,6 +10,7 @@ from flask_pyoidc.user_session import UserSession
from backend import app from backend import app
from backend.auth import oidc_auth from backend.auth import oidc_auth
from backend.auth.oidc_config import PROVIDER_NAME
fe_path = os.path.abspath(os.path.join(app.root_path, os.pardir, os.pardir, "frontend", "dist")) fe_path = os.path.abspath(os.path.join(app.root_path, os.pardir, os.pardir, "frontend", "dist"))
if not os.path.exists(fe_path) or not os.path.exists(os.path.join(fe_path, "index.html")): if not os.path.exists(fe_path) or not os.path.exists(os.path.join(fe_path, "index.html")):
@@ -37,7 +38,7 @@ def send_img(path):
@fe_bp.route('/test') @fe_bp.route('/test')
@oidc_auth.oidc_auth() @oidc_auth.oidc_auth(provider_name=PROVIDER_NAME)
def test_oidc(): def test_oidc():
user_session = UserSession(flask.session) user_session = UserSession(flask.session)
access_token = user_session.access_token access_token = user_session.access_token