0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Githubでアクセストークンを使う

Last updated at Posted at 2024-12-16

Githubのアクセストークン

CLIからgitを使っていて、認証しようと思った場合の選択肢は以下の2つになります
(以前はIDパスワード認証もありました現在は使えなくなっています)

・SSH
・PAT (Personal Access Token)

上記のうち、SSHは権限設定や期限付き発行ができません。一方で、PATは権限を細かく設定できて期限付き発行がデフォルトであることから環境ごとに権限の異なるトークンを発行できるのがメリットです

作成する

repository permission内のcodeのwrite権限があればpushしたりbranch/mergeしたりできます

使い方

githubにアクセスする際のURLを https://ユーザーネーム:入手したトークン@github.com/ のようにするとアクセストークンを適用できます

自分のアカウントが https://hoge@github.com/ の場合は
https://hoge:ここにアクセストークン@github.com/ になります

環境全体で登録する

.gitconfigでurlの置き換えを設定できるので、以下のように書いてやればurlにアクセストークンを自動で挿入してくれます

~/.gitconfig
[url "https://hoge:入手したトークン@github.com/"]
	insteadOf = https://github.com/

.gitconfigを超苦節操作しても良いですが、git configで登録することもできます

terminal
$ git config --global url.https://ユーザーネーム:入手したトークン@github.com/.insteadOf https://github.com/

上記だと.gitconfigに追記されるので、既に登録している場合は場合は以下のように1度消してから登録する必要があります

terminal
$ git config --global --unset-all url.https://github.com/.insteadOf
$ git config --global url.https://ユーザーネーム:入手したトークン2@github.com/.insteadOf https://github.com/

リポジトリ単位で登録する

リポジトリ単位の情報はリポジトリフォルダの.gitディレクトリ内のconfigに書いてあるのでORIGINを以下のように編集してやることでアクセストークンが使えます

/.git/config
[remote "origin"]
	url = https://アクセストークン@github.com/ユーザー名/リポジトリ名
	fetch = +refs/heads/*:refs/remotes/origin/*

参考にしたページ

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?