如何在CLI中获取GitHub API Token?替代已弃用的创建方式
First, let's set the context clearly:
Previously, we could create GitHub personal access tokens by sending a request to api.github.com/authorizations, passing in the username, password, and specifying the token's scope. However, this feature was deprecated on November 13, 2020, and no direct replacement has been introduced yet. GitHub recommends using the web application flow, which isn't ideal for CLI tool development since it pulls users out of the terminal environment.
If you need a way to generate tokens without forcing users to manually navigate to settings, here are practical, CLI-native solutions:
Leverage the official GitHub CLI (
gh)
This is the most supported and straightforward option. GitHub's official CLI is built to handle auth flows seamlessly in the terminal. Here's how to use it:- Ensure
ghis installed (it’s available for Windows, macOS, and Linux). - Run
gh auth loginand follow the prompts:- Select your account type (GitHub.com or Enterprise).
- Choose the Login with a web browser option—while it requires opening a browser, it’s optimized for CLI workflows: you’ll get a one-time code to enter in the browser, and once authenticated, the CLI automatically creates a token with the scopes you specify.
- To skip prompt-based scope selection, use
gh auth login --scopes repo,admin:org(replace the scopes with your tool’s specific needs).
- Post-login, the token is stored in the CLI’s config, and you can retrieve it for your tooling with
gh auth token.
- Ensure
Implement the OAuth 2.0 Device Authorization Grant (Device Flow)
This flow is purpose-built for CLI/desktop apps where redirecting to a browser isn’t ideal. Here’s the high-level workflow:- Your CLI sends a request to GitHub’s device authorization endpoint to get a
device_code,user_code, andverification_uri. - Display these details to the user (e.g., "Open your browser and go to [uri], then enter code: [user_code]").
- Your CLI polls GitHub’s token endpoint at regular intervals until the user completes authorization in their browser.
- Once authorized, you’ll receive an access token to use for API requests.
This keeps the user anchored in the CLI—they only need a browser open to enter the code, no manual token creation in settings required.
- Your CLI sends a request to GitHub’s device authorization endpoint to get a
Use reputable community CLI tools (with caution)
Some community-maintained CLI tools wrap the device flow or other auth methods to simplify token creation. Always vet these tools thoroughly (audit their code, check for active maintenance) to avoid security risks before integrating them into your workflow.
It’s important to note that GitHub removed password-based token creation for security reasons, so these OAuth-based flows are the only supported, secure alternatives that preserve a CLI-first experience.
内容的提问来源于stack exchange,提问作者user137369

