AWS Cognito с Apache Superset в Docker: «Ошибка: неверный вход. Повторите попытку».Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 AWS Cognito с Apache Superset в Docker: «Ошибка: неверный вход. Повторите попытку».

Сообщение Anonymous »

Я пытаюсь интегрировать AWS Cognito с Superset.
Superset работает в Docker.
До внедрения Cognito все загружалось нормально — суперсет работает.
На моей странице https://momo.com/login/ я нажимаю кнопку «Войти с помощью Cognito», и меня перенаправляют в домен AWS для входа в систему. Там я ввожу свои учетные данные, а затем 2FA, и после успешного выполнения этого вместо перенаправления на панели мониторинга расширенного набора меня отправляют обратно на страницу входа https://momo.com/login/ с ошибкой « Неверный логин. Повторите попытку."
Когда я проверяю журналы, я вижу следующее:
2024-12-01 19:41:02,182 - WARNING - Class 'werkzeug.local.LocalProxy' is not mapped
2024-12-01 19:41:51,768 - ERROR - Error returning OAuth user info:

Я пробовал реализовать МНОГО разных журналов, но они ничего не возвращали, поэтому я удалил их здесь для ясности. Ошибки и предупреждения выше — лучшее, что я получил.
  • Я понизил версию инструмента «wekzeug» до другой версии, чтобы посмотреть, есть ли какие-либо улучшения — ничего.
  • Я думаю, проблема может быть где-то в логике кода.
    Я почти уверен, что конфигурация Cognito в AWS настроена правильно.
Вот мой superset_config.py:
# Superset Configuration
RATELIMIT_STORAGE_URI = 'redis://redis:9999/0'
ENABLE_PROXY_FIX = True
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_SAMESITE = "Lax"
SUPERSET_WEBSERVER_PROTO = 'https'

# Import necessary modules
import os
import json
import logging
from flask_appbuilder.security.manager import AUTH_OAUTH # Import AUTH_OAUTH directly from flask_appbuilder
from authlib.integrations.flask_client import OAuth # Import Authlib for OAuth
from flask import request, redirect, url_for, session
from jose import jwt # Import jwt for decoding the token
import time # For checking expiration

# Set up logging
log_dir = '/log/my_logs'
log_file = os.path.join(log_dir, 'my_debug.log')

# Enable OAuth authentication
AUTH_TYPE = AUTH_OAUTH

# Define Cognito's OAuth provider details
OAUTH_PROVIDERS = [{
'name': 'cognito',
'token_key': 'access_token', # OAuth token key
'icon': 'fa-cogs',
'remote_app': {
'client_id': '111',
'client_secret': 'xxx', # Replace with actual client secret
'base_url': 'https://cognito-idp.eu-central-1.amazon ... l-1_123456',
'request_token_url': None, # Cognito does not require this
'access_token_url': 'https://momo1.auth.eu-central-1.amazonc ... uth2/token', # Cognito token URL
'authorize_url': 'https://momo1.auth.eu-central-1.amazonc ... /authorize', # Cognito login URL
'access_token_method': 'POST',
'api_base_url': 'https://momo1.auth.eu-central-1.amazoncognito.com', # Cognito IDP base URL
}
}]

# Configure the callback URL for OAuth
OAUTH_REDIRECT_URI = "https://momo.com/oauth-authorized/cognito"

# OAuth Token Exchange Logic with scopes
def exchange_oauth_code_for_token(code, state):
"""Exchange the OAuth code for tokens, with scopes."""
app = appbuilder.get_app() # Initialize the app instance
oauth = OAuth(app)

cognito = oauth.register(
'cognito',
client_id='111',
client_secret='xxx', # Replace with actual client secret
authorize_url='https://momo1.auth.eu-central-1.amazonc ... /authorize',
access_token_url='https://momo1.auth.eu-central-1.amazonc ... uth2/token',
access_token_method='POST',
api_base_url='https://momo1.auth.eu-central-1.amazoncognito.com',
)

try:
# Exchange the code for the access token and ID token, with scopes
scopes = ['openid', 'email', 'profile']

# Exchange the code for the access token and ID token, with scopes
token = cognito.fetch_access_token(
code=code,
redirect_uri=OAUTH_REDIRECT_URI,
scope=' '.join(scopes) # Pass scopes as a space-separated string
)

return token
except Exception as e:
return None

# OAuth Callback Logic
def oauth_authorized_callback():
""" Handle the OAuth callback from Cognito. """
code = request.args.get('code')
state = request.args.get('state')

if not code:
return redirect(url_for('login')) # Redirect if no code is found

# Exchange the authorization code for tokens
token = exchange_oauth_code_for_token(code, state)
if not token:
return redirect(url_for('login')) # Redirect if token exchange fails

# Store the tokens in the session for future use
session['access_token'] = token['access_token']
session['id_token'] = token['id_token']

# Check if the access token is valid
if not check_token_validity():
return redirect(url_for('login')) # Redirect if token is invalid

# Fetch user info from Cognito using the access token
oauth = OAuth(appbuilder.get_app()) # Reinitialize OAuth instance
cognito = oauth.register(
'cognito',
client_id='111',
client_secret='xxx', # Replace with actual client secret
api_base_url='https://momo1.auth.eu-central-1.amazoncognito.com',
)

try:
user_info_response = cognito.get('https://cognito-idp.eu-central-1.amazon ... 6/userinfo', token=session['access_token'])
user_info = user_info_response.json() # Parse the response to get user data

# Optionally store user info for further use
session['user_info'] = user_info

# Ensure the user is registered in Superset (using email as unique identifier)
if user_info:
user = appbuilder.sm.find_user(email=user_info.get('email'))
if not user:
user = appbuilder.sm.add_user(
username=user_info.get('email'),
first_name=user_info.get('name'),
last_name=user_info.get('name'),
email=user_info.get('email'),
role=appbuilder.sm.find_role("Admin") # Or use any default role
)
except Exception as e:
return redirect(url_for('login')) # Redirect if user info fetch fails

# Redirect to the appropriate authenticated page (Superset Dashboard)
return redirect("https://momo.com/superset/dashboard/dashboard_1/")

# Additional settings for OAuth
AUTH_USER_REGISTRATION = True
AUTH_USER_REGISTRATION_ROLE = "Admin"



Подробнее здесь: https://stackoverflow.com/questions/792 ... se-try-aga
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»