Skip to content

Instantly share code, notes, and snippets.

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

This comment has been minimized.

Copy link

commented Feb 6, 2018

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


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 ='/'.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:
session.headers.update({'Private-Token': private_token})

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


  • 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.