首页 > 解决方案 > 如何使用个人访问令牌而不是使用 shell 脚本的密码来访问 Github API

问题描述

最近好吗?

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

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

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

标签: bashgithubgithub-api

解决方案


用于--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


推荐阅读