Git push requires username and password

2018-12-31 08:31发布

I cloned a git repository from my Github account to my PC.

I want to work with both my PC and laptop, but with one Github account.

When I try to push to or pull from Github using my PC, it requires username and password, but not when using the laptop!

I don't want to type my username and password every time I interact with origin. What I am missing here?

20条回答
怪性笑人.
2楼-- · 2018-12-31 09:22

A common mistake is cloning using the default (HTTPS) instead of SSH. You can correct this by going to your repository, clicking "Clone or download", then clicking the "Use SSH" button above the URL field and updating the URL of your origin remote like this:

git remote set-url origin git@github.com:username/repo.git

This is documented at GitHub: Switching remote URLs from HTTPS to SSH.

查看更多
临风纵饮
3楼-- · 2018-12-31 09:24

When you use https for git pull & push, just config remote.origin.url for your project, to avoid input username (or/and password) everytime you push.

How to config remote.origin.url:

Url format:
    https://{username:password@}github.com/{owner}/{repo}

Parameters in url:
* username
    optional, the username to use when need authentication,
    if specified, no need to enter username again when need authentication,
    don't use email, use your username that has no "@", otherwise the url can't be parsed correctly,
* password
    optional, the password to use when need authentication,
    if specified, no need to enter password again when need authentication,
    tip:
        this value is stored as plain text, so for security concern, don't specify this param,
* 

e.g
    git config remote.origin.url https://eric@github.com/eric/myproject


@Update - using ssh

I think using ssh protocol is a better solution than https, even though the setup step is a little more complex.

Rough steps:

  • Create ssh keys using command, e.g ssh-keygen on linux, on windows msysgit provide similar commands.
  • Keep private key on local machine at proper location, e.g ~/.ssh. And add it to ssh agent via ssh-add command.
  • Upload the public key to git server.
  • Change remote.origin.url of git repository to ssh style, e.g git@gitlab.com:myaccount/myrepo.git
  • Then when pull or push, no need to enter username or password ever.

Tips:

  • If your ssh key has a passphrase, then you need to input it on first use of the key after each restart of your machine, by default.

@Update - Switch between https and ssh protocol.

Simply change remote.origin.url will be enough, or you can edit repo_home/.git/config directly to change the value (e.g using vi on linux).

Usually I add a line for each protocol, and comment out one of them using #.

e.g

[remote "origin"]
        url = git@gitlab.com:myaccount/myrepo.git
        # url = https://myaccount@gitlab.com/myaccount/myrepo.git
        fetch = +refs/heads/*:refs/remotes/origin/*
查看更多
登录 后发表回答