Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
python-gitlab login/password auth using cookies
import re
import sys
import requests
import gitlab
URL = 'https://gitlab.com'
SIGN_IN_URL = 'https://gitlab.com/users/sign_in'
LOGIN_URL = 'https://gitlab.com/users/sign_in'
session = requests.Session()
sign_in_page = session.get(SIGN_IN_URL).content
for l in sign_in_page.split('\n'):
m = re.search('name="authenticity_token" value="([^"]+)"', l)
if m:
break
token = None
if m:
token = m.group(1)
if not token:
print('Unable to find the authenticity token')
sys.exit(1)
data = {'user[login]': 'login_or_email',
'user[password]': 'SECRET',
'authenticity_token': token}
r = session.post(LOGIN_URL, data=data)
if r.status_code != 200:
print('Failed to log in')
sys.exit(1)
gl = gitlab.Gitlab(URL, api_version=4, session=session)
@knusperkrone

This comment has been minimized.

Copy link

commented Feb 6, 2018

Could you please add an open-source license for this gist?

@fcollonval

This comment has been minimized.

Copy link

commented Jun 7, 2018

Thanks for the gist!

Unfortunately non-GET requests are forbidden when using session cookie. But having the session cookie we can continue the hack to get a private access token:

page_tokens = session.get('/'.join((URL, 'profile/personal_access_tokens')))
private_token = None
if page_tokens.ok:
    root = bs4.BeautifulSoup(page_tokens.text, "html5lib")
    token = root.find_all("form", id='new_personal_access_token')[0].find_all('input', attrs={'name': 'authenticity_token'})[0]['value']

    body = {
      "personal_access_token[name]": 'mytoken',
      "personal_access_token[scopes][]": 'api',
      'authenticity_token': token
    }

    response = session.post('/'.join((URL, 'profile/personal_access_tokens')), data=body)

    if response.ok:
        private_token_page = bs4.BeautifulSoup(response.text, "html5lib")
        private_token = private_token_page.find_all('input', id='created-personal-access-token')[0]['value']

if not private_token:
    sys.exit(1)
session.headers.update({'Private-Token': private_token})

gl = gitlab.Gitlab(URL, api_version=4, session=session)

Remarks:

  • I used BeautifoulSoup to help parsing HTML pages
  • Duplicated names are allowed for access token name - but it will be better to avoid regenerating a new token every time you call the script.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.