gpt4 book ai didi

python - 通过 gitlab oauth 使用 mattermost api 作为具有用户名和密码的最终用户(无 client_secret)

转载 作者:太空狗 更新时间:2023-10-29 17:19:39 26 4
gpt4 key购买 nike

在我们的团队中,我们使用 gitlab ( https://git.example ) 和捆绑的 mattermost 聊天 ( https://chat.example )。

最重要的是,我们希望有一个专门的 bot 用户(网络 Hook 在私有(private) channel 等方面有限制),它实际上可以像普通用户一样登录。

我们在 gitlab 中创建了该用户,并可以通过 chrome 登录我们的聊天(聊天登录 redir --> gitlab oauth,输入用户名和密码 --> redir 返回聊天 --> authed)。

现在我搜索了实际上可以执行此操作的 python 库,但我只能找到一些需要 client_idclient_secret 的库...根据我的理解(请更正我,如果我错了)这不是我们正在寻找的,因为我们不想创建另一个应用程序来通过 gitlab 进行身份验证,而是登录到我们的聊天室(它已经有一个 id (已知)和一个 secret(未知))作为用户通过 gitlab。

由于找不到这样的库,我们还检查了 chrome 中的网络请求,并尝试通过 requests 在 python 中重新创建它,但无法让它工作(不需要说它涉及解析 html 和 csrf token )...

再次尝试和大量猜测,我们尝试通过手动获取 access_token

client_id = 'the one of mattermost in our gitlab'
user = 'username'
pw = 'password'
r = requests.post(
'https://git.example/oauth/token',
data={
"grant_type": "password",
"username": user,
"password": pw,
"client_id": client_id,
}
)
access_token = r.json()['access_token']

这似乎可行(并且 token 看起来不错),但在最重要的 API 中使用它只会导致 401:

ri = requests.get(
'https://chat.example/api/v1/users/me',
headers={'Authorization': 'Bearer ' + access_token}
)

ri.status_code, ri.json()
(401,
{u'detailed_error': u'token=...xxx...',
u'id': u'api.context.session_expired.app_error',
u'is_oauth': False,
u'message': u'Invalid or expired session, please login again.',
u'request_id': u'...yyy...',
u'status_code': 401})

悲哀http://docs.mattermost.com/developer/web-service.html#oauth2目前没有对此有更多的了解,这就是我在这里问的原因。我是否错过了一些明显的东西来“激活”mattermost 中的 access_token

最佳答案

实际上我最终通过如下模仿浏览器的行为来运行它,但我仍然对不涉及解析任何 gitlab 服务器的 html 的更通用的解决方案感兴趣...:

import requests
from pyquery import PyQuery as pq

client_id = '...your_mattermost_client_id...'
user = '...username...'
pw = '...userpass...'

gitlab = 'https://git.example'
chat = 'https://chat.example'
team = '/your_team'

r = requests.get(
chat + team + '/login/gitlab'
)
q = pq(r.content)
csrf_token = q('#new_ldap_user input[name="authenticity_token"]')[0].value # watch out, several tokens for ldap vs. normal login, inspect the page to find correct one

r2 = requests.post(
gitlab + '/users/auth/ldapmain/callback', # or whatever the browser callback for your auth-method was
cookies=r.cookies,
data={
'authenticity_token': csrf_token,
'username': user,
'password': pw,
}
)

# print [h.url for h in r2.history] + [r2.url] # to check the redirects

me = requests.get(
chat + '/api/v1/users/me',
cookies=r2.cookies,
)
print me.json() # if everything went well you're now authorized

# remember to set cookies in the follow-up requests

关于python - 通过 gitlab oauth 使用 mattermost api 作为具有用户名和密码的最终用户(无 client_secret),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36650437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com