问题:
使用github用户名和密码无法登陆。报错如下:
liyane@Yans-MacBook-Air git % git clone https://github.com/<my git account>/repo2023.git
Cloning into 'repo2023'...
Username for 'https://github.com': <my user name>
Password for 'https://<my user name>@github.com':
remote: Support for password authentication was removed on August 13, 2021.
就像报错信息显示的,Git在2021年8月13日之后不再支持用户名和密码方式的身份验证。
那么如何通过身份验证呢?
解答1:最简单的方法之一,使用Token登陆。
1. 创建令牌Token。
用户可以通过创建和使用令牌token登陆Github。可以生成多张令牌,每张令牌拥有不同的时效和权限,分发给不同的用户或者设备,从而控制令牌的使用。
要创建令牌,可以使用浏览器登陆Github你的账号profile页面。
然后选择Developer settings,打开开发者配置页面。
选择Personal Access Tokens/Tokens(classic)/Create new token(classic)。
- 令牌的名字:自定义,比如my mac。
- 令牌时效:可选择永不过期。作为管理员,可以删掉以前颁发的令牌。
- 令牌权限:按需要选择。
记下生成的令牌,这个令牌只在创建时显示一次。
2. 使用 Token在本地连接github仓库
在自己的机器上,使用如下命令配置和连接名为origin的在GitHub上的repo(例子中是repo2023)。
#从远端的代码库克隆代码到本地
git clone https://<my token>@github.com:<my git account>/repo2023.git
#成功以后,信息会记在本地目录下边的.git/config文件中。你以后再执行git命令就不用再输入令牌了。远程的代码库在本地的默认名字"origin"。#cat .git/config
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
precomposeunicode = true
[remote "origin"]
url = https://<my token>@github.com:<my git account>/repo2023.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "main"]
remote = origin
注:替换该命令中的令牌<my token>,Github账号<my git account>和repo名字。
解答2:使用SSH登陆
SSH也是比较流行的登陆方式。通过密钥对来完成验证。
1. 创建SSH密钥对。
用户首先需要一对SSH密钥。公钥添加到Github中。私钥只存储在自己的机器上,是身份的证明。
SSH密钥对可以通过以下命令创建:
ssh-keygen -t ed25519 -C "<注释>"
-t为种类参数,支持rsa或者ed25519等
-C为注释参数
要求Enter passphrase时,直接回车,输入空值
密钥对默认生成在用户默认目录的.ssh隐藏目录下。带后缀.pub名字的文件为公钥。
2. 将公钥添加在Github中。
可以使用浏览器登陆Github你的账号profile页面。
然后选择Access/SSH and GPG keys。
点击New SSH key按钮。
- SSH key的名字:自定义,比如my mac。
- Key type: Authentication Key
- Key: 将.pub公钥文件中的内容复制在此。
3. 在本地连接github仓库
在自己的机器上,使用如下命令配置和连接GitHub上的代码库(例子中是repo2023)。
#从远端的代码库克隆代码到本地
git clone git@github.com:<my git account>/repo2023.git
#成功以后,信息会记在本地目录下边的.git/config文件中。远程的代码库在本地的默认名字"origin"。
#cat .git/config
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
precomposeunicode = true
[remote "origin"]
url = git@github.com:<my git account>/repo2023.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "main"]
remote = origin