SSH Keys, Tokens, and 2FA
Modern Git platforms (like GitHub and GitLab) support secure authentication mechanisms to manage repository access. SSH keys, personal access tokens (PATs), and two-factor authentication (2FA) play a critical role in safeguarding your work.
1. SSH Keys
SSH keys offer a secure, password-less way to authenticate with Git remotes over SSH.
a. Generate an SSH Key
ssh-keygen -t ed25519 -C "your_email@example.com"
This creates a public and private key pair in ~/.ssh/.
b. Add Your SSH Key to the SSH Agent
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
c. Add the Public Key to GitHub
Copy the contents of your public key:
cat ~/.ssh/id_ed25519.pub
Paste it into: GitHub > Settings > SSH and GPG Keys > New SSH Key
2. Personal Access Tokens (PATs)
With HTTPS-based Git remotes, password authentication is no longer supported. Instead, use Personal Access Tokens.
- Tokens act like passwords with limited scope and expiration.
- Can be used in Git clients, CLI, or API access.
a. Generate a Token (GitHub)
GitHub > Settings > Developer Settings > Personal Access Tokens
Choose scopes such as repo, workflow, or admin:org.
b. Use with HTTPS
When prompted for a password during git clone or git push, paste your token instead.
You can also embed it in your Git remote URL:
https://<username>:<token>@github.com/username/repo.git
3. Two-Factor Authentication (2FA)
2FA adds a second layer of protection beyond just a password.
- Typically uses TOTP apps like Google Authenticator or Authy.
- Prevents unauthorized access even if your password is compromised.
a. Enable 2FA (GitHub)
GitHub > Settings > Password and Authentication > Two-Factor Authentication
Scan the QR code with your TOTP app and save recovery codes.
Summary
| Feature | Purpose | Use Case |
|---|---|---|
| SSH Keys | Secure password-less access | Daily CLI operations, long-lived access |
| PATs | Token-based HTTPS authentication | CI jobs, automation, GUI clients |
| 2FA | Secondary authentication factor | Account-level security and login protection |