diff --git a/enterprise/server/auth/constants.py b/enterprise/server/auth/constants.py index c01525a43d..15d3b0f704 100644 --- a/enterprise/server/auth/constants.py +++ b/enterprise/server/auth/constants.py @@ -30,3 +30,11 @@ JIRA_DC_CLIENT_SECRET = os.getenv('JIRA_DC_CLIENT_SECRET', '').strip() JIRA_DC_BASE_URL = os.getenv('JIRA_DC_BASE_URL', '').strip() JIRA_DC_ENABLE_OAUTH = os.getenv('JIRA_DC_ENABLE_OAUTH', '1') in ('1', 'true') AUTH_URL = os.getenv('AUTH_URL', '').rstrip('/') +ROLE_CHECK_ENABLED = os.getenv('ROLE_CHECK_ENABLED', 'false').lower() in ( + '1', + 'true', + 't', + 'yes', + 'y', + 'on', +) diff --git a/enterprise/server/routes/auth.py b/enterprise/server/routes/auth.py index 3976363ee4..c9e92d54f7 100644 --- a/enterprise/server/routes/auth.py +++ b/enterprise/server/routes/auth.py @@ -12,6 +12,7 @@ from server.auth.constants import ( KEYCLOAK_CLIENT_ID, KEYCLOAK_REALM_NAME, KEYCLOAK_SERVER_URL_EXT, + ROLE_CHECK_ENABLED, ) from server.auth.gitlab_sync import schedule_gitlab_repo_sync from server.auth.saas_user_auth import SaasUserAuth @@ -133,6 +134,12 @@ async def keycloak_callback( user_info = await token_manager.get_user_info(keycloak_access_token) logger.debug(f'user_info: {user_info}') + if ROLE_CHECK_ENABLED and 'roles' not in user_info: + return JSONResponse( + status_code=status.HTTP_401_UNAUTHORIZED, + content={'error': 'Missing required role'}, + ) + if 'sub' not in user_info or 'preferred_username' not in user_info: return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST,