Git authentication with GitLab personal access tokens

25 April, 2025
git GitLab DevOps

GitLab's personal access tokens allow you to authenticate to your private GitLab repository without using an SSH key or setting up credentials in some other way. I like to use this method with short-lived access tokens as an easy and relatively secure way to interact with my private GitLab repositories. This may not be the best way for you.

In almost every instance that I'm pushing code to GitLab, I'm going to be logged in to GitLab at the same time. So, I create a short-lived personal access token for that session. For some reason this doesn't seem to be clearly documented, but when you create a personal access token, give it the same name as the repository it's used for, and it'll be scoped to that repo. I just give it API access, and set an expiry of one day.

Then, in my local Git instance, I update the URL of the remote repository to include that token:

git remote set-url origin https://oauth2:<token>@gitlab.com/<username>/<repo>.git

For example,

git remote set-url origin https://oauth2:abcdefg1234567@gitlab.com/hedsnz/hedsnz-public.git

Note that this sets the token in plain text in your Git configuration. For me personally, this is not an attack vector that I'm worried about: If my local machine is compromised, then a short-lived personal access token to a private GitLab repository is the least of my concerns. And of course, it expires in one day anyway.

You can also supply the personal access token with each request, so that it's not saved in your Git configuration. The official docs describe this well. This Stack Overflow post is also a good reference.