How to update an expired Personal Access Token (PAT) in Git?

Following my other "quick" guides (also known as personal notes 🤣) like How to solve the ReferenceError Document is not defined issue?, I decided to write this short one, just to provide a direct answer to anyone looking for this on Google.

1. The situation

I was working in a GitLab project and... I was not able to fetch / pull the latest changes:

shell
remote: HTTP Basic: Access denied. If a password was provided for Git authentication, the password was incorrect or you're required to use a token instead of a password. If a token was provided, it was either incorrect, expired, or improperly scoped. See <https://gitlab.com/help/topics/git/troubleshooting_git.md#error-on-git-fetch-http-basic-access-denied>
fatal: Authentication failed for '<https://gitlab.com/*********/************.git/>'

Basically, I had my PAT (Personal Access Token) expired. So... time to renew it.

2. Get the new token

I was using GitLab but wherever you are hosting the repo, you will have a way to generate a new personal access token. Just do it.

In case you are using GitLab, here is a direct link.

3. Updating Git

Once you have the token, it is time to open a terminal in the root directory of the project with the expired token.

The first command to run is:

shell
git config --get remote.origin.url

Why? Because you will need to "build" the new origin URL by updating its token.

Probably your command return will look like this:

text
<https://<YOUR_GIT_USER>:<YOUR_EXPIRED_PAT_TOKEN>@gitlab.com/********/************.git>

Building the new origin URL

Now just replace the expired PAT token stirng with the new you generated, so you have a new URL like this:

text
<https://<YOUR_GIT_USER>:<YOUR_NEW_PAT_TOKEN>@gitlab.com/****>

Updating Git

Now you can run the following command (replacing it with your new URL):

shell
 git config remote.origin.url <YOUR_NEW_ORIGIN_URL>

4. That's it!

If you now fetch or pull, it should work. That was easy, wasn't it?

shell
git fetch && git pull