實(shí)現(xiàn)流程
1、獲取 OAuthenticator 源碼
git clone https://github.com/jupyterhub/oauthenticator.git
2魄懂、添加飛書登錄代碼 oauthenticator/oauthenticator/feishu.py
"""
FeiShu Authenticator with JupyterHub
"""
import os
from jupyterhub.auth import LocalAuthenticator
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
from traitlets import Bool, List, Unicode, default
from .oauth2 import OAuthenticator
import json
class FeiShuOAuthenticator(OAuthenticator):
login_service = 'FeiShu'
tls_verify = Bool(
os.environ.get('OAUTH2_TLS_VERIFY', 'True').lower() in {'true', '1'},
config=True,
help="Disable TLS verification on http request",
)
allowed_groups = List(
Unicode(),
config=True,
help="Automatically allow members of selected groups",
)
admin_groups = List(
Unicode(),
config=True,
help="Groups whose members should have Jupyterhub admin privileges",
)
@default("http_client")
def _default_http_client(self):
return AsyncHTTPClient(force_instance=True, defaults=dict(validate_cert=self.tls_verify))
def _get_app_access_token(self):
req = HTTPRequest(
'https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal/',
method="POST",
headers={
'Content-Type': "application/json; charset=utf-8",
},
body=json.dumps({
'app_id': self.client_id,
'app_secret': self.client_secret
}),
)
return self.fetch(req, "fetching app access token")
def _get_user_access_token(self, app_access_token, code):
req = HTTPRequest(
'https://open.feishu.cn/open-apis/authen/v1/access_token',
method="POST",
headers={
'Content-Type': "application/json; charset=utf-8",
'Authorization': f'Bearer {app_access_token}'
},
body=json.dumps({
"grant_type": "authorization_code",
"code": code
}),
)
return self.fetch(req, "fetching user access token")
def _get_user_info(self, user_access_token, union_id):
req = HTTPRequest(
f'https://open.feishu.cn/open-apis/contact/v3/users/{union_id}?user_id_type=union_id',
method="GET",
headers={
'Content-Type': "application/json; charset=utf-8",
'Authorization': f'Bearer {user_access_token}'
}
)
return self.fetch(req, "fetching user info")
@staticmethod
def _create_auth_state(token_response, user_info):
access_token = token_response['access_token']
refresh_token = token_response.get('refresh_token', None)
scope = token_response.get('scope', '')
if isinstance(scope, str):
scope = scope.split(' ')
return {
'access_token': access_token,
'refresh_token': refresh_token,
'oauth_user': user_info,
'scope': scope,
}
@staticmethod
def check_user_in_groups(member_groups, allowed_groups):
return bool(set(member_groups) & set(allowed_groups))
async def authenticate(self, handler, data=None):
code = handler.get_argument("code")
app_access_token_resp = await self._get_app_access_token()
user_access_token_resp = await self._get_user_access_token(app_access_token_resp['app_access_token'], code)
user_info_resp = await self._get_user_info(user_access_token_resp['data']['access_token'], user_access_token_resp['data']['union_id'])
self.log.info("user is %s", json.dumps(user_info_resp))
user_info = user_info_resp['data']['user']
user_info = {
'name': user_info['name'],
'auth_state': self._create_auth_state(user_access_token_resp['data'], user_info)
}
if self.allowed_groups:
self.log.info('Validating if user claim groups match any of {}'.format(self.allowed_groups))
groups = user_info['department_ids']
if self.check_user_in_groups(groups, self.allowed_groups):
user_info['admin'] = self.check_user_in_groups(groups, self.admin_groups)
else:
user_info = None
return user_info
class LocalFeiShuOAuthenticator(LocalAuthenticator, FeiShuOAuthenticator):
"""A version that mixes in local system user creation"""
pass
3、集成 OAuthenticator 到 JupyterHub 官方 Docker 鏡像
首先觅廓,添加文件 oauthenticator/Dockerfile
FROM jupyterhub/jupyterhub
RUN pip3 install notebook
ADD . .
RUN pip3 install -e .
然后茂翔,修改 oauthenticator/setup.py
,在 'jupyterhub.authenticators'
數(shù)組中添加如下內(nèi)容:
'feishu= oauthenticator.feishu:FeiShuOAuthenticator',
'local-feishu = oauthenticator.feishu:LocalFeiShuOAuthenticator',
最后涧尿,構(gòu)建鏡像
docker build -t jupyterhub .
4系奉、新建 JupyterHub 配置文件
新建文件 ~/jupyterhub_config.py
,內(nèi)容如下:
import pwd
import subprocess
from oauthenticator.feishu import FeiShuOAuthenticator
c.JupyterHub.authenticator_class = FeiShuOAuthenticator
app_id = '<飛書企業(yè)自建應(yīng)用 app_id>'
app_secret = '<飛書企業(yè)自建應(yīng)用 app_secret>'
c.FeiShuOAuthenticator.authorize_url = 'https://open.feishu.cn/open-apis/authen/v1/index'
c.FeiShuOAuthenticator.extra_authorize_params = {'redirect_uri': 'http://127.0.0.1:8000/hub/oauth_callback', 'app_id': app_id}
c.FeiShuOAuthenticator.client_id = app_id
c.FeiShuOAuthenticator.client_secret = app_secret
def pre_spawn_hook(spawner):
username = spawner.user.name
try:
pwd.getpwnam(username)
except KeyError:
subprocess.check_call(['useradd', '-ms', '/bin/bash', username])
c.Spawner.pre_spawn_hook = pre_spawn_hook
提醒:飛書應(yīng)用后臺需配置「安全設(shè)置」「重定向 URL」姑廉,添加
http://127.0.0.1:8000/hub/oauth_callback
5缺亮、測試飛書登錄
使用 Docker 啟動 JupyterHub
docker run -it --rm \
-p 8000:8000 \
-v ~/jupyterhub_config.py:/srv/jupyterhub/jupyterhub_config.py \
jupyterhub \
jupyterhub -f /srv/jupyterhub/jupyterhub_config.py
啟動成功后,訪問 http://127.0.0.1:8000/ 即可測試飛書登錄桥言。