mirror of
https://github.com/YFGaia/dify-plus.git
synced 2026-06-26 16:02:18 +08:00
fix: 修正oauth2.0登录失败问题
This commit is contained in:
+101
-16
@@ -141,6 +141,47 @@ class GoogleOAuth(OAuth):
|
||||
# Extend Start: OAuth2
|
||||
class OaOAuth(OAuth):
|
||||
|
||||
def _is_absolute_url(self, url: str) -> bool:
|
||||
return isinstance(url, str) and (url.startswith("http://") or url.startswith("https://"))
|
||||
|
||||
def _join_url(self, base: str, path_or_url: str) -> str:
|
||||
if not path_or_url:
|
||||
return ""
|
||||
if self._is_absolute_url(path_or_url):
|
||||
return path_or_url
|
||||
return f"{base}{path_or_url}"
|
||||
|
||||
def _resolve_endpoints(self, config: dict) -> dict:
|
||||
"""
|
||||
Resolve authorize/token/userinfo endpoints from config or OIDC discovery.
|
||||
"""
|
||||
if not isinstance(config, dict):
|
||||
return {}
|
||||
server_url = config.get('server_url') or ''
|
||||
authorize_url = config.get('authorize_url') or ''
|
||||
token_url = config.get('token_url') or ''
|
||||
userinfo_url = config.get('userinfo_url') or ''
|
||||
discovery_url = config.get('discovery_url') or ''
|
||||
|
||||
# If any endpoint missing and discovery available, fetch
|
||||
if discovery_url and (not authorize_url or not token_url or not userinfo_url):
|
||||
try:
|
||||
discover_full = self._join_url(server_url, discovery_url)
|
||||
resp = requests.get(discover_full, timeout=10)
|
||||
if resp.ok:
|
||||
data = resp.json()
|
||||
authorize_url = authorize_url or data.get('authorization_endpoint', '')
|
||||
token_url = token_url or data.get('token_endpoint', '')
|
||||
userinfo_url = userinfo_url or data.get('userinfo_endpoint', '')
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return {
|
||||
'authorize_url': self._join_url(server_url, authorize_url),
|
||||
'token_url': self._join_url(server_url, token_url),
|
||||
'userinfo_url': self._join_url(server_url, userinfo_url),
|
||||
}
|
||||
|
||||
def get_auto2_conf(self):
|
||||
# oauth start
|
||||
integration = db.session.query(SystemIntegrationExtend).filter(
|
||||
@@ -193,30 +234,51 @@ class OaOAuth(OAuth):
|
||||
if integration is None:
|
||||
return
|
||||
# 构建查询参数
|
||||
query_string = urllib.parse.urlencode({
|
||||
config = auto2_conf.get('config')
|
||||
params = {
|
||||
'response_type': 'code',
|
||||
'redirect_uri': dify_config.CONSOLE_API_URL + "/console/api/oauth/authorize/oauth2",
|
||||
'client_id': integration.app_id,
|
||||
})
|
||||
# 重要:未设置 scope 时,Casdoor /api/userinfo 仅返回 openid 最小字段
|
||||
# 从配置读取 scope,默认请求更完整的信息
|
||||
'scope': (config.get('scope') if isinstance(config, dict) and config.get('scope') else 'openid profile email'),
|
||||
}
|
||||
if invite_token:
|
||||
params['state'] = invite_token
|
||||
query_string = urllib.parse.urlencode(params)
|
||||
|
||||
# 构建完整URL
|
||||
config = auto2_conf.get('config')
|
||||
return f"{config.get('server_url')}{config.get('authorize_url')}?{query_string}"
|
||||
endpoints = self._resolve_endpoints(config)
|
||||
auth_url = endpoints.get('authorize_url')
|
||||
return f"{auth_url}?{query_string}"
|
||||
|
||||
def get_access_token(self, code: str):
|
||||
auto2_conf = self.get_auto2_conf()
|
||||
integration = auto2_conf.get('integration')
|
||||
if integration is None:
|
||||
return ""
|
||||
config = auto2_conf.get('config')
|
||||
endpoints = self._resolve_endpoints(config)
|
||||
token_url = endpoints.get('token_url')
|
||||
token_auth_method = str(config.get('token_auth_method') or '').strip().lower()
|
||||
use_basic = token_auth_method == 'client_secret_basic'
|
||||
|
||||
# 构建请求
|
||||
data = {
|
||||
"code": code,
|
||||
"client_id": integration.app_id,
|
||||
"grant_type": "authorization_code",
|
||||
"client_secret": auto2_conf.get('passwd'),
|
||||
"code": code,
|
||||
"redirect_uri": dify_config.CONSOLE_API_URL + "/console/api/oauth/authorize/oauth2",
|
||||
}
|
||||
headers = {"Accept": "application/json"}
|
||||
config = auto2_conf.get('config')
|
||||
response = requests.post(f"{config.get('server_url')}{config.get('token_url')}", data=data, headers=headers)
|
||||
if use_basic:
|
||||
auth = (integration.app_id, auto2_conf.get('passwd'))
|
||||
else:
|
||||
data.update({
|
||||
"client_id": integration.app_id,
|
||||
"client_secret": auto2_conf.get('passwd'),
|
||||
})
|
||||
auth = None
|
||||
|
||||
response = requests.post(token_url, data=data, headers=headers, auth=auth)
|
||||
response.encoding = "utf-8"
|
||||
if response.status_code != 200:
|
||||
return ""
|
||||
@@ -233,8 +295,9 @@ class OaOAuth(OAuth):
|
||||
if auto2_conf.get('integration') is None:
|
||||
return ""
|
||||
config = auto2_conf.get('config')
|
||||
endpoints = self._resolve_endpoints(config)
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
response = requests.get(f"{config.get('server_url')}{config.get('userinfo_url')}", headers=headers)
|
||||
response = requests.get(endpoints.get('userinfo_url'), headers=headers)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
@@ -247,13 +310,35 @@ class OaOAuth(OAuth):
|
||||
name="",
|
||||
email="",
|
||||
)
|
||||
# 提取参数
|
||||
# 提取参数(更健壮:支持点分路径、扁平键名和标准 OIDC 兜底)
|
||||
config = auto2_conf.get('config')
|
||||
name = self.extract_data(raw_info, config.get('user_name_field'))
|
||||
email = self.extract_data(raw_info, config.get('user_email_field'))
|
||||
username = self.extract_data(raw_info, config.get('user_id_field'))
|
||||
name_field = config.get('user_name_field') if isinstance(config, dict) else None
|
||||
email_field = config.get('user_email_field') if isinstance(config, dict) else None
|
||||
id_field = config.get('user_id_field') if isinstance(config, dict) else None
|
||||
|
||||
# 首选:按配置路径提取
|
||||
name = self.extract_data(raw_info, name_field) if name_field else None
|
||||
email = self.extract_data(raw_info, email_field) if email_field else None
|
||||
username = self.extract_data(raw_info, id_field) if id_field else None
|
||||
|
||||
# 如果配置为 data.name 但返回是扁平结构,尝试最后一级键名
|
||||
if name is None and isinstance(name_field, str) and '.' in name_field:
|
||||
name = raw_info.get(name_field.split('.')[-1])
|
||||
if email is None and isinstance(email_field, str) and '.' in email_field:
|
||||
email = raw_info.get(email_field.split('.')[-1])
|
||||
if username is None and isinstance(id_field, str) and '.' in id_field:
|
||||
username = raw_info.get(id_field.split('.')[-1])
|
||||
|
||||
# OIDC 常见字段兜底
|
||||
if username is None:
|
||||
username = raw_info.get('sub') or raw_info.get('preferred_username') or raw_info.get('id') or raw_info.get('user_id')
|
||||
if name is None:
|
||||
name = raw_info.get('name') or raw_info.get('preferred_username')
|
||||
if email is None:
|
||||
email = raw_info.get('email')
|
||||
|
||||
if not username:
|
||||
raise ValueError("OAuth2返回用户数据格式不正确。请返回进行重新登录。")
|
||||
raise ValueError("OAuth2返回用户数据格式不正确。请检查相关配置是否正确。响应信息为:" + str(raw_info))
|
||||
|
||||
return OAuthUserInfo(
|
||||
id=str(username) if username is not None else None,
|
||||
|
||||
Reference in New Issue
Block a user