如何使用个人访问令牌而不是使用Shell脚本访问密码来访问Github API

时间:2020-08-26 16:00:17

标签: bash github github-api

进展如何?

因此,我使用bash脚本来创建一个远程存储库,该存储库使用密码来访问这样的端点:

NEWVAR="{\"name\":\"$githubrepo\",\"private\":\"true\"}"
curl -u $USERNAME https://api.github.com/user/repos -d "$NEWVAR"

但是,GitHub不再允许开发人员使用密码访问端点。所以我的问题是如何使用个人访问令牌创建远程存储库?

1 个答案:

答案 0 :(得分:1)

使用--header传输授权:

#!/usr/bin/env sh

github_user='The GitHub user name'
github_repo='The repository name'

github_oauth_token='The GitHub API auth token'

# Create the JSON data payload arguments needed to create
# a GitHub repository.
json_data="$(
  jq \
    --null-input \
    --compact-output \
    --arg name "$github_repo" \
    '{$name, "private":true}'
)"

if json_reply="$(
  curl \
    --fail \
    --request POST \
    --header 'Accept: application/vnd.github.v3+json' \
    --header "Authorization: token $github_oauth_token" \
    --header 'Content-Type: application/json' \
    --data "$json_data" \
    'https://api.github.com/user/repos'
)"; then
  # Save the JSON answer of the repository creation
  printf '%s' "$json_reply" >"$github_repo.json"
  printf 'Successfully created the repository: %s\n' "$github_repo"
else
  printf 'Could not create the repository: %s\n' "$github_repo" >&2
  printf 'The GitHub API replied with this JSON:\n%s\n' "$json_reply" >&2
fi

在此处查看我的答案,以获取具有特色的实现示例: https://stackoverflow.com/a/57634322/7939871