2016-04-15 1 views
14

私たちのチームでは、gitlab(https://git.example)とバンドルされたほとんどのチャット(https://chat.example)を使用します。gitlab oauthを使って重要なapiをユーザー名とパスワードを持つエンドユーザーとして使用します(client_secretなし)

ほとんどの場合、専用のボットユーザー(Webフックにはプライベートチャンネルなどの制限があります)があります。実際には通常のユーザーとまったく同じようにログインします。

gitlabでそのユーザーを作成し、chrome(chat login redir - > gitlab oauth、usernameを入力、pw - > redirをチャット - > authed)でチャットにログインできます。

私は実際にこれを行うことができるPythonライブラリを探しましたが、私はclient_idclient_secretを必要とするものしか見つけられません...私の理解から(私が間違っている場合は私を修正してください) gitlabで認証する別のアプリケーションを作成するのではなく、gitlabを使ってユーザとしてチャット(既にid(既知)とsecret(未知)を持っている)にログインしているので、

私たちはこのようなライブラリを見つけることができなかったので、ネットワークリクエストをchromeで調べ、requests経由でpythonで再作成しようとしましたが、動作させることはできません(もちろん、htmlそして、CSRFトークンを)...

我々は

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'] 

これが動作しているようです(とトークンがよさそうだ)、それを使用して手動access_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はこれ以上のことを明らかにしていないため、私はここで尋ねています。私は多分何かの中でaccess_tokenを "活性化"する明白な何かを逃したでしょうか? ...

答えて

9

は、実際に私は最終的に次のようにブラウザの挙動を模倣することによって、このランニングを得たが、私はまだ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 
関連する問題