JupyterHub 集成飛書授權(quán)登錄

實(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/ 即可測試飛書登錄桥言。

參考資料

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末萌踱,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子号阿,更是在濱河造成了極大的恐慌并鸵,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,273評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件扔涧,死亡現(xiàn)場離奇詭異园担,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)枯夜,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,349評論 3 398
  • 文/潘曉璐 我一進(jìn)店門弯汰,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人湖雹,你說我怎么就攤上這事咏闪。” “怎么了摔吏?”我有些...
    開封第一講書人閱讀 167,709評論 0 360
  • 文/不壞的土叔 我叫張陵鸽嫂,是天一觀的道長织鲸。 經(jīng)常有香客問我,道長溪胶,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,520評論 1 296
  • 正文 為了忘掉前任稳诚,我火速辦了婚禮哗脖,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘扳还。我一直安慰自己才避,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,515評論 6 397
  • 文/花漫 我一把揭開白布氨距。 她就那樣靜靜地躺著桑逝,像睡著了一般。 火紅的嫁衣襯著肌膚如雪俏让。 梳的紋絲不亂的頭發(fā)上楞遏,一...
    開封第一講書人閱讀 52,158評論 1 308
  • 那天,我揣著相機(jī)與錄音首昔,去河邊找鬼寡喝。 笑死,一個胖子當(dāng)著我的面吹牛勒奇,可吹牛的內(nèi)容都是我干的预鬓。 我是一名探鬼主播,決...
    沈念sama閱讀 40,755評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼赊颠,長吁一口氣:“原來是場噩夢啊……” “哼格二!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起竣蹦,我...
    開封第一講書人閱讀 39,660評論 0 276
  • 序言:老撾萬榮一對情侶失蹤顶猜,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后痘括,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體驶兜,經(jīng)...
    沈念sama閱讀 46,203評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,287評論 3 340
  • 正文 我和宋清朗相戀三年远寸,在試婚紗的時候發(fā)現(xiàn)自己被綠了抄淑。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,427評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡驰后,死狀恐怖肆资,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情灶芝,我是刑警寧澤郑原,帶...
    沈念sama閱讀 36,122評論 5 349
  • 正文 年R本政府宣布唉韭,位于F島的核電站,受9級特大地震影響犯犁,放射性物質(zhì)發(fā)生泄漏属愤。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,801評論 3 333
  • 文/蒙蒙 一酸役、第九天 我趴在偏房一處隱蔽的房頂上張望住诸。 院中可真熱鬧,春花似錦涣澡、人聲如沸贱呐。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,272評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽奄薇。三九已至,卻和暖如春抗愁,著一層夾襖步出監(jiān)牢的瞬間馁蒂,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評論 1 272
  • 我被黑心中介騙來泰國打工蜘腌, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留远搪,地道東北人。 一個月前我還...
    沈念sama閱讀 48,808評論 3 376
  • 正文 我出身青樓逢捺,卻偏偏與公主長得像谁鳍,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子劫瞳,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,440評論 2 359

推薦閱讀更多精彩內(nèi)容