glab-auth
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chineseglab auth
glab auth
Manage GitLab CLI authentication.
管理 GitLab CLI 身份认证。
Environment credentials and trusted hosts
环境凭据与受信任主机
Environment , , and settings resolve only for trusted hosts: the effective default (including / / , or under CI auto-login; otherwise the configured default or ), a host in the configuration's map, or the host of a user-set URL or value. A bare value does not add trust. HTTP(S) host comparisons retain ports; SSH repository URLs use the hostname without the SSH port.
tokenjob_tokenis_oauth2hostGITLAB_HOSTGITLAB_URIGL_HOSTCI_SERVER_FQDNgitlab.comhostsGITLAB_REPOgit@host:pathHOST/OWNER/REPOAn arbitrary host supplied only through a command argument, such as a full-URL repository selector, does not receive environment credentials. glab warns when it withholds an environment token. This restriction does not remove explicit per-host stored credentials. Inspect the intended host and actor before approving authentication or changing a host selector; do not add an untrusted destination to configuration merely to suppress a warning. Non-secret environment-backed settings such as still resolve normally, so review those routing settings too.
api_host环境中的 、 和 设置仅对受信任主机生效:生效的默认 (包括 / / ,或在 CI 自动登录时使用 ;否则为配置的默认值或 )、配置中 map 内的主机,或用户设置的 URL / 值的主机。裸 值不会建立信任。比较 HTTP(S) 主机时会保留端口;SSH 仓库 URL 使用不含 SSH 端口的主机名。
tokenjob_tokenis_oauth2hostGITLAB_HOSTGITLAB_URIGL_HOSTCI_SERVER_FQDNgitlab.comhostsGITLAB_REPOgit@host:pathHOST/OWNER/REPO仅通过命令参数提供的任意主机(例如完整 URL 形式的仓库选择器)不会获得环境凭据。glab 在扣留环境 token 时会发出警告。此限制不会移除按主机显式存储的凭据。在批准身份认证或更改主机选择器之前,请检查目标主机和操作者;不要仅为消除警告就将不受信任的目标加入配置。诸如 这类非机密的环境支持设置仍会正常解析,因此也应检查这些路由设置。
api_hostDefault host after login
登录后的默认主机
Successful login can change the global default used outside a Git repository. If the default is still and there are no credentials for it, glab selects the newly authenticated host automatically. Existing credentials, including an environment token, prevent that automatic switch; unreadable credential storage is treated conservatively. Otherwise interactive login asks first, while non-interactive login prints the command for a separate approved change. CI and a set , , or leave the configured default unchanged. A default-host update failure is a warning after successful authentication.
hostgitlab.comglab config set --global host <host>GITLAB_HOSTGITLAB_URIGL_HOSTInside a checkout, remote-host selection takes precedence over the configured fallback host; an environment-selected host is authoritative and errors when no remote matches it. Verify the host after login before subsequent writes.
The Git credential helper formats its response from the resolved credential: a job token uses , a personal token uses the configured host username (falling back to ), and an OAuth credential uses plus available expiry/refresh fields. Do not infer which token was returned from a separate config lookup. The helper remains a credential-producing command, so do not run it for diagnostics or print its output.
gitlab-ci-tokenglaboauth2job_token登录成功后,可能更改在 Git 仓库之外使用的全局默认 。如果默认值仍为 且其中没有凭据,glab 会自动选择新完成身份认证的主机。已有凭据(包括环境 token)会阻止此自动切换;凭据存储不可读时则采取保守处理。否则,交互式登录会先询问,而非交互式登录会输出 命令,以便单独批准这项更改。CI 以及已设置的 、 或 会使配置的默认值保持不变。默认主机更新失败仅作为身份认证成功后的警告。
hostgitlab.comglab config set --global host <host>GITLAB_HOSTGITLAB_URIGL_HOST在 checkout 中,远程主机的选择优先于配置的备用主机;由环境选定的主机具有权威性,如果没有匹配的 remote 则会报错。后续写入前,请验证登录后的主机。
Git credential helper 根据解析出的凭据格式化响应:job token 使用 ,个人 token 使用配置的主机用户名(回退为 ),OAuth 凭据使用 并附带可用的过期/刷新字段。不要根据单独查询 配置来推断返回的是哪个 token。该 helper 仍是一个会生成凭据的命令,因此不要将其用于诊断,也不要打印其输出。
gitlab-ci-tokenglaboauth2job_tokenGeneric credential-helper protocol
通用 credential-helper 协议
glab auth credential-helperauth statustypetype: "error"codemessagenot_authenticatedunsupported_auth_sourcerefresh_failedkeyring_unavailableinvalid_repo_overrideunknownhostoauth_errorinvalid_grantOn an OAuth-only instance with personal access tokens disabled, glab can supply Git HTTP(S) credentials and refresh OAuth tokens without an OAuth client secret. GitLab.com uses the built-in client ID; Self-Managed and Dedicated require an administrator-created OAuth application and its client ID, shared across users. After approval for the exact host and persistent glab configuration write, first run with that application's public client ID, never its secret. writes this per-host setting to glab's global configuration. Then, after approval of login and the host-specific global Git configuration change, run (or without a local browser). Without a configured client ID, Self-Managed/Dedicated login prompts interactively or fails non-interactively; it does not fall back to GitLab.com's client ID.
glab config set client_id <CLIENT_ID> --host <host>--hostglab auth login --hostname <host> --web --setup-git-credential-helper--deviceglab auth credential-helperauth statustypetype: "error"codemessagenot_authenticatedunsupported_auth_sourcerefresh_failedkeyring_unavailableinvalid_repo_overrideunknownhostinvalid_grantoauth_error在仅支持 OAuth 且已禁用 personal access token 的实例上,glab 可以在没有 OAuth client secret 的情况下提供 Git HTTP(S) 凭据并刷新 OAuth token。GitLab.com 使用内置 client ID;Self-Managed 和 Dedicated 需要管理员创建 OAuth application 及其 client ID,并由所有用户共享。在批准针对确切主机的操作并允许持久化 glab 配置写入后,首先运行 ,使用该 application 的 public client ID,绝不能使用 secret。 会将此按主机设置写入 glab 的全局配置。然后,在批准登录以及针对该主机的全局 Git 配置更改后,运行 (或在无本地浏览器时使用 )。如果未配置 client ID,Self-Managed/Dedicated 登录会交互式提示,或在非交互环境中失败;它不会回退使用 GitLab.com 的 client ID。
glab config set client_id <CLIENT_ID> --host <host>--hostglab auth login --hostname <host> --web --setup-git-credential-helper--deviceNon-interactive Git credential helper
非交互式 Git credential helper
glab auth login --setup-git-credential-helper--stdinbash
glab auth login --hostname gitlab.example.com --stdin --setup-git-credential-helper < token.txtKeep the approved token file outside Git and out of logs. Missing keyring entries follow normal credential resolution; locked, denied, or unavailable keyring failures are surfaced. Reauthenticate for the intended host when no usable token remains; do not silently switch identities or weaken storage.
glab auth login --setup-git-credential-helper--stdinbash
glab auth login --hostname gitlab.example.com --stdin --setup-git-credential-helper < token.txt将已批准的 token 文件保存在 Git 之外且不要写入日志。缺少 keyring 条目时遵循正常的凭据解析流程;keyring 被锁定、拒绝访问或不可用时,相应失败会直接显示。当没有可用 token 时,应针对目标主机重新进行身份认证;不要静默切换身份,也不要削弱存储安全性。
Quick start
快速开始
bash
undefinedbash
undefinedInteractive login
Interactive login
glab auth login
glab auth login
Browser/OAuth login without the prompt
Browser/OAuth login without the prompt
glab auth login --hostname gitlab.com --web
glab auth login --hostname gitlab.com --web
Check current auth status
Check current auth status
glab auth status
glab auth status
Login to different instance
Login to different instance
glab auth login --hostname gitlab.company.com
glab auth login --hostname gitlab.company.com
Logout
Logout
glab auth logout
undefinedglab auth logout
undefinedWorkflows
工作流
Machine-readable authentication status
机器可读的身份认证状态
bash
glab auth status --hostname gitlab.example.com --output json
glab auth status --all --output json
glab auth status --all --output json --jq '.hosts[] | {host, state, user}'JSON contains a array with per-host state, user (when available), endpoint, protocol, token-source, warning, and error metadata. It never contains the token itself; is rejected with JSON output. Omitted optional fields should not be mistaken for empty credentials. Check both exit status and each host's state before any write, and verify the intended actor independently with . Keep paired with .
hosts--show-tokenglab api user--jq--output jsonbash
glab auth status --hostname gitlab.example.com --output json
glab auth status --all --output json
glab auth status --all --output json --jq '.hosts[] | {host, state, user}'JSON 包含一个 数组,其中包含各主机的 state、user(可用时)、endpoint、protocol、token-source、warning 和 error 元数据。它绝不包含 token 本身;在 JSON 输出中使用 会被拒绝。不要将省略的可选字段误认为空凭据。在任何写入前,同时检查退出状态和每个主机的 state,并使用 独立验证目标操作者。务必将 与 搭配使用。
hosts--show-tokenglab api user--jq--output jsonFirst-time setup
首次设置
- Run
glab auth login - Choose authentication method (token or browser)
- Follow prompts for your GitLab instance
- Verify with
glab auth status
supports a complete setup flow:glab auth login
to explicitly set a different API/Web endpoint for self-hosted instances--api-host to explicitly set a different SSH endpoint for self-hosted instances--ssh-hostname to skip the login-type prompt and go straight to browser/OAuth auth--web to preconfigure registry / dependency-proxy domains during login--container-registry-domainsExample: API hostname, SSH hostnamegitlab.company.comssh.company.com
For personal access tokens, glab requires at least and . GitLab 18.9 introduced ; that route does not exist on earlier releases. GitLab 18.8 and earlier use instead. Use the URL for the target instance rather than assuming the current GitLab.com route exists on an older self-managed server.
apiwrite_repositoryhttps://<host>/-/user_settings/personal_access_tokens/legacy/new?scopes=api,write_repositoryhttps://<host>/-/user_settings/personal_access_tokens?scopes=api,write_repositoryIn non-interactive login, omitting resolves the target in this order: the base repository's GitLab remote, , the configuration , then . For credential writes, prefer an explicit when the surrounding repository or environment is not intentionally authoritative.
--hostnameGITLAB_HOSThostgitlab.com--hostnameIn interactive login, environment-backed configuration values pre-answer their matching setup questions only on the matching path. selects the instance before remote detection. and skip the matching endpoint prompts when the hostname comes from or ; if you choose the instance-menu "GitLab Self-Managed or GitLab Dedicated instance" path, glab still prompts for endpoint hostnames unless you supply and . , , and skip their own registry-domain and protocol prompts. Explicit command flags remain clearer for one-off credential writes and should be preferred when shell state is not tightly controlled.
GITLAB_HOSTGITLAB_API_HOSTGITLAB_SSH_HOST--hostnameGITLAB_HOST--api-host--ssh-hostnameGLAB_CONTAINER_REGISTRY_DOMAINSGLAB_GIT_PROTOCOLGLAB_API_PROTOCOLFor browser/OAuth login to GitLab Self-Managed or GitLab Dedicated, glab now guides interactive setup when no OAuth application ID is configured. Choose either to paste an existing Application ID or to print the exact registration values for an instance/group administrator. The "show me what an admin needs to create" choice only prints the redirect URI, scopes, and requirement, then exits the login attempt non-zero with the same "set first" error. After the admin creates the application, rerun login after either saving the ID with or exporting ; printing the registration values is not a way to continue the same login attempt. Never paste an application secret into the Application ID prompt. A newly pasted ID is persisted only after a successful OAuth round trip. In non-interactive environments, preconfigure it explicitly with or supply .
Confidential: offclient_idglab config set client_id <client_id> -g --host <hostname>GITLAB_CLIENT_IDglab config set client_id <client_id> -g --host <hostname>GITLAB_CLIENT_ID- 运行
glab auth login - 选择身份验证方式(token 或浏览器)
- 按照提示配置你的 GitLab 实例
- 使用 验证
glab auth status
支持完整的设置流程:glab auth login
用于为自托管实例显式设置不同的 API/Web endpoint--api-host 用于为自托管实例显式设置不同的 SSH endpoint--ssh-hostname 用于跳过登录类型提示,直接进入浏览器/OAuth 身份认证--web 用于在登录期间预配置 registry / dependency-proxy 域名--container-registry-domains示例:API hostname 为,SSH hostname 为gitlab.company.comssh.company.com
对于 personal access token,glab 要求至少具备 和 scope。GitLab 18.9 引入了 ;早期版本中不存在该路径。GitLab 18.8 及更早版本改用 。请使用目标实例对应的 URL,不要假定较旧的自托管服务器上存在当前的 GitLab.com 路径。
apiwrite_repositoryhttps://<host>/-/user_settings/personal_access_tokens/legacy/new?scopes=api,write_repositoryhttps://<host>/-/user_settings/personal_access_tokens?scopes=api,write_repository在非交互式登录中,省略 时,目标按以下顺序解析:基础仓库的 GitLab remote、、配置中的 ,然后是 。对于凭据写入,当周围仓库或环境并非有意作为权威来源时,优先显式指定 。
--hostnameGITLAB_HOSThostgitlab.com--hostname在交互式登录中,环境支持的配置值只有在路径匹配时才会预先回答相应设置问题。 会在 remote 检测之前选定实例。当 hostname 来自 或 时, 和 会跳过相应的 endpoint 提示;如果选择实例菜单中的“GitLab Self-Managed or GitLab Dedicated instance”路径,除非提供 和 ,否则 glab 仍会提示输入 endpoint hostname。、 和 会分别跳过 registry 域名和协议提示。对于一次性凭据写入,显式命令标志通常更清晰;当 shell 状态未受到严格控制时,应优先使用它们。
GITLAB_HOST--hostnameGITLAB_HOSTGITLAB_API_HOSTGITLAB_SSH_HOST--api-host--ssh-hostnameGLAB_CONTAINER_REGISTRY_DOMAINSGLAB_GIT_PROTOCOLGLAB_API_PROTOCOL对于面向 GitLab Self-Managed 或 GitLab Dedicated 的浏览器/OAuth 登录,如果未配置 OAuth application ID,glab 现在会引导交互式设置。可以粘贴现有 Application ID,也可以打印实例/群组管理员创建应用所需的准确值。选择“告诉我管理员需要创建什么”只会打印 redirect URI、scopes 和 要求,然后以相同的“先设置 ”错误非零退出登录尝试。管理员创建 application 后,重新运行登录;在此之前应使用 保存 ID,或导出 。打印注册信息并不能继续当前登录尝试。绝不要把 application secret 粘贴到 Application ID 提示中。新粘贴的 ID 仅在 OAuth 往返成功后持久化。在非交互环境中,使用 显式预配置,或提供 。
Confidential: offclient_idglab config set client_id <client_id> -g --host <hostname>GITLAB_CLIENT_IDglab config set client_id <client_id> -g --host <hostname>GITLAB_CLIENT_IDLogin flag examples
登录标志示例
Token login through or persists container-registry domains for the selected host too. Resolution prefers an explicit , then the configured value (including environment-backed configuration), then hostname-derived defaults. This preserves custom domains on re-login and makes them available to the Docker credential helper. Verify with before configuring Docker. This persistence behavior applies to the personal-token path; do not assume the separate path has the same setup behavior.
--token--stdin--container-registry-domainsglab config get container_registry_domains --host <hostname>--job-tokenbash
undefined通过 或 进行 token 登录时,也会为选定主机持久保存 container-registry 域名。解析优先级依次为:显式 、配置值(包括环境支持配置)、从主机名派生的默认值。这样可在重新登录时保留自定义域名,并使其可供 Docker credential helper 使用。在配置 Docker 前,使用 验证。此持久化行为适用于个人 token 路径;不要假定独立的 路径具有相同设置行为。
--token--stdin--container-registry-domainsglab config get container_registry_domains --host <hostname>--job-tokenbash
undefinedPersonal-token login with explicit registry domains; keep the token file outside Git
Personal-token login with explicit registry domains; keep the token file outside Git
glab auth login --hostname gitlab.company.com --stdin
--api-protocol https --git-protocol ssh
--container-registry-domains "registry.gitlab.company.com,gitlab.company.com"
< approved-token-file glab config get container_registry_domains --host gitlab.company.com
--api-protocol https --git-protocol ssh
--container-registry-domains "registry.gitlab.company.com,gitlab.company.com"
< approved-token-file glab config get container_registry_domains --host gitlab.company.com
glab auth login --hostname gitlab.company.com --stdin
--api-protocol https --git-protocol ssh
--container-registry-domains "registry.gitlab.company.com,gitlab.company.com"
< approved-token-file glab config get container_registry_domains --host gitlab.company.com
--api-protocol https --git-protocol ssh
--container-registry-domains "registry.gitlab.company.com,gitlab.company.com"
< approved-token-file glab config get container_registry_domains --host gitlab.company.com
Self-managed GitLab with separate API and SSH endpoints
Self-managed GitLab with separate API and SSH endpoints
glab auth login
--hostname gitlab.company.com
--ssh-hostname ssh.company.com
--hostname gitlab.company.com
--ssh-hostname ssh.company.com
glab auth login
--hostname gitlab.company.com
--ssh-hostname ssh.company.com
--hostname gitlab.company.com
--ssh-hostname ssh.company.com
Skip prompts and go straight to browser/OAuth auth
Skip prompts and go straight to browser/OAuth auth
glab auth login --hostname gitlab.com --web
glab auth login --hostname gitlab.com --web
Preconfigure multiple registry / dependency proxy domains during login
Preconfigure multiple registry / dependency proxy domains during login
glab auth login
--hostname gitlab.com
--web
--container-registry-domains "registry.gitlab.com,gitlab.com"
--hostname gitlab.com
--web
--container-registry-domains "registry.gitlab.com,gitlab.com"
glab auth login
--hostname gitlab.com
--web
--container-registry-domains "registry.gitlab.com,gitlab.com"
--hostname gitlab.com
--web
--container-registry-domains "registry.gitlab.com,gitlab.com"
Supply every self-managed endpoint so only browser authorization remains interactive
Supply every self-managed endpoint so only browser authorization remains interactive
glab auth login --hostname gitlab.example.com --web
--api-host gitlab.example.com --ssh-hostname gitlab.example.com
--api-protocol https --git-protocol ssh
--container-registry-domains registry.gitlab.example.com
--api-host gitlab.example.com --ssh-hostname gitlab.example.com
--api-protocol https --git-protocol ssh
--container-registry-domains registry.gitlab.example.com
glab auth login --hostname gitlab.example.com --web
--api-host gitlab.example.com --ssh-hostname gitlab.example.com
--api-protocol https --git-protocol ssh
--container-registry-domains registry.gitlab.example.com
--api-host gitlab.example.com --ssh-hostname gitlab.example.com
--api-protocol https --git-protocol ssh
--container-registry-domains registry.gitlab.example.com
Explicitly opt out of keyring storage (stores the token as plaintext)
Explicitly opt out of keyring storage (stores the token as plaintext)
glab auth login --hostname gitlab.company.com --insecure-storage
--stdin < approved-token-file
--stdin < approved-token-file
undefinedglab auth login --hostname gitlab.company.com --insecure-storage
--stdin < approved-token-file
--stdin < approved-token-file
undefinedCredential storage
凭据存储
On a normal workstation, stores credentials in the operating system keyring by default when one is available: macOS Keychain, Windows Credential Manager, or Linux Secret Service. The old flag is deprecated because keyring storage is now the default. Re-running login migrates a credential previously stored as plaintext in the config file into the keyring.
glab auth login--use-keyringUse only when plaintext config-file storage is explicitly required and its risk is accepted. If no keyring backend is available, glab warns and falls back to the config file. In CI ( or is set), glab defaults to config-file storage because keyrings are usually unavailable or ephemeral; prefer environment credentials rather than persisting a login there.
--insecure-storageGITLAB_CICIIf a keyring is locked, unavailable, or denies access, glab reports the credential-read failure directly. Fix keyring access or re-authenticate instead of treating the resulting error as an invalid token.
glab checks whether refreshed OAuth credentials can be saved before it refreshes the token, and serializes credential writes across concurrent processes. If multiple agents or shells share one config directory, prefer separate config directories per actor for isolation, but do not add external file locks around itself.
glabglabOAuth access tokens are refreshed with a five-minute grace period instead of waiting until they are effectively expired. If the token is still usable but refreshed credentials cannot be saved, glab keeps using the current token rather than turning the save probe into an immediate outage. For a self-managed instance under a subfolder, refresh requests use the configured subfolder; keep the exact host setting when diagnosing token refresh URLs.
subfolderIn a sandbox such as Claude Code, must be allowed to write the directory from , not only the file. writes a temporary file beside the config and then replaces the original. On snap installs, connect keyring access with if encrypted credential storage is required; otherwise can fall back to plaintext config storage.
glabglab config path --dirconfig.ymlglabsudo snap connect glab:password-manager-serviceglab auth loginWhen re-authenticating interactively, preserves saved per-host values such as a custom API host, SSH host, and container-registry domains unless you explicitly override them with flags or prompts. Verify these values after re-authentication instead of deleting the config preemptively:
glabbash
glab config get api_host --host gitlab.company.com
glab config get ssh_host --host gitlab.company.com
glab config get container_registry_domains --host gitlab.company.comNon-interactive login also persists explicitly supplied and values in the host configuration. This applies to token/stdin and other prompt-free login paths, so automation can configure the protocols in the same login operation instead of requiring a later config edit. Verify the resulting host entry before relying on it:
--git-protocol--api-protocolbash
glab auth login --hostname gitlab.company.com --stdin \
--git-protocol ssh --api-protocol https < approved-token-file
glab config get git_protocol --host gitlab.company.com
glab config get api_protocol --host gitlab.company.comKeep token files outside version control and do not print their contents.
CI auto-login: lets glab use in GitLab CI/CD without a stored login. , , and still take precedence, so leave them unset when the intended credential is . Use explicit env tokens instead when a command needs a project, group, or personal access token.
GLAB_ENABLE_CI_AUTOLOGIN=trueCI_JOB_TOKENGITLAB_TOKENGITLAB_ACCESS_TOKENOAUTH_TOKENCI_JOB_TOKEN在普通工作站上, 默认将凭据存储在操作系统的 keyring 中(如果可用):macOS Keychain、Windows Credential Manager 或 Linux Secret Service。旧的 标志已弃用,因为 keyring 存储现在是默认方式。重新运行登录会将先前以明文存储在配置文件中的凭据迁移到 keyring。
glab auth login--use-keyring仅当明确需要明文配置文件存储且已接受相关风险时,才使用 。如果没有可用的 keyring 后端,glab 会发出警告并回退到配置文件。在 CI( 或 已设置)中,glab 默认使用配置文件存储,因为 keyring 通常不可用或生命周期短暂;在那里应优先使用环境凭据,而不是持久保存登录状态。
--insecure-storageGITLAB_CICI如果 keyring 被锁定、不可用或拒绝访问,glab 会直接报告凭据读取失败。请修复 keyring 访问权限或重新进行身份认证,不要将由此产生的错误视为无效 token。
glab 会在刷新 token 前检查刷新后的 OAuth 凭据能否保存,并串行化并发 glab 进程间的凭据写入。如果多个 Agent 或 shell 共享一个配置目录,为实现隔离,应优先让每个操作者使用独立的配置目录,但不要在 glab 之外添加文件锁。
OAuth access token 会提前五分钟刷新,而不是等到其实际过期。如果 token 仍可用但刷新后的凭据无法保存,glab 会继续使用当前 token,而不会让保存探测立即导致服务中断。对于位于子文件夹下的自托管实例,刷新请求会使用配置的 subfolder;诊断 token 刷新 URL 时,请保留 host 设置的准确值。
subfolder在 Claude Code 等 sandbox 中,必须允许 glab 写入 返回的目录,而不只是 文件。glab 会在配置文件旁写入临时文件,然后替换原文件。对于 snap 安装,如需加密凭据存储,请使用 连接 keyring 访问;否则 可回退到明文配置存储。
glab config path --dirconfig.ymlsudo snap connect glab:password-manager-serviceglab auth login交互式重新认证时, 会保留已保存的按主机值,例如自定义 API host、SSH host 和 container-registry 域名,除非你通过标志或提示显式覆盖它们。请在重新认证后验证这些值,而不是提前删除配置:
glabbash
glab config get api_host --host gitlab.company.com
glab config get ssh_host --host gitlab.company.com
glab config get container_registry_domains --host gitlab.company.com非交互式登录还会将显式提供的 和 值持久保存到主机配置中。这适用于 token/stdin 及其他无需提示的登录路径,因此自动化可以在一次登录操作中配置协议,而无需稍后编辑配置。在依赖这些值之前,请验证最终的主机条目:
--git-protocol--api-protocolbash
glab auth login --hostname gitlab.company.com --stdin \
--git-protocol ssh --api-protocol https < approved-token-file
glab config get git_protocol --host gitlab.company.com
glab config get api_protocol --host gitlab.company.com将 token 文件保存在版本控制之外,不要打印其内容。
CI 自动登录: 允许 glab 在 GitLab CI/CD 中使用 ,而无需存储登录状态。、 和 仍具有更高优先级,因此当目标凭据为 时,请不要设置这些变量。当命令需要项目、群组或个人 access token 时,请改用显式环境 token。
GLAB_ENABLE_CI_AUTOLOGIN=trueCI_JOB_TOKENGITLAB_TOKENGITLAB_ACCESS_TOKENOAUTH_TOKENCI_JOB_TOKENAgentic and multi-account setups
Agent 与多账户设置
If you need different agents to show up as different GitLab users, use distinct GitLab bot/service accounts. Multiple PATs on one GitLab user are useful for rotation or scope separation, but they do not create distinct visible identities.
Use the Actor identity for actor-authored GitLab comments, replies, approvals, and other writes. Use an agent identity only when the GitLab action is explicitly that agent's own work product. Pick the intended visible actor before the first write.
A good operational pattern is one env file per actor:
bash
undefined如果需要让不同 Agent 显示为不同的 GitLab 用户,请使用不同的 GitLab bot/service account。单个 GitLab 用户拥有多个 PAT 有助于轮换或按 scope 分离,但不会创建不同的可见身份。
对于 Agent 撰写的 GitLab 评论、回复、审批及其他写入,使用 Actor identity。仅当 GitLab 操作明确属于该 Agent 自身的工作产物时,才使用 agent identity。首次写入前选定目标可见 actor。
一种良好的运维模式是为每个 actor 使用一个 env 文件:
bash
undefined~/.config/openclaw/env/gitlab-reviewer.env
~/.config/openclaw/env/gitlab-reviewer.env
GITLAB_TOKEN=glpat-...
GITLAB_HOST=gitlab.com
Keep these env files outside version control, restrict their permissions (for example `chmod 600`), be mindful of backup exposure, and prefer least-privilege bot/service-account tokens. In a reused shell, clear stale GitLab auth vars first or start a fresh shell.
If the file uses plain `KEY=value` lines, load it with exported vars before running `glab`:
```bash
unset GITLAB_TOKEN GITLAB_ACCESS_TOKEN OAUTH_TOKEN GITLAB_HOST
set -a
source ~/.config/openclaw/env/gitlab-<actor>.env
set +aWhy this matters:
- plain does not necessarily export variables to child processes
source - only sees env vars that are exported
glab - if cannot see the env token, it may silently fall back to shared stored auth in the active global config file
glab - if another env file was sourced earlier in the same shell/session, identity can be sticky in ways that are unsafe for writes unless you deliberately switch and verify
That fallback/shared-auth behavior is convenient for humans, but in multi-agent automation it can cause the wrong GitLab account to post comments, create MRs, or approve work.
GITLAB_TOKEN=glpat-...
GITLAB_HOST=gitlab.com
将这些 env 文件保存在版本控制之外,限制其权限(例如 `chmod 600`),注意备份泄露风险,并优先使用最小权限的 bot/service-account token。在复用的 shell 中,应先清除过期的 GitLab 认证变量,或者启动新的 shell。
如果文件使用普通的 `KEY=value` 行,请在运行 `glab` 前导出变量:
```bash
unset GITLAB_TOKEN GITLAB_ACCESS_TOKEN OAUTH_TOKEN GITLAB_HOST
set -a
source ~/.config/openclaw/env/gitlab-<actor>.env
set +a这样做的原因:
- 普通 不一定会将变量导出到子进程
source - 只能看到已导出的环境变量
glab - 如果 无法看到环境 token,它可能会静默回退到当前全局配置文件中的共享存储认证
glab - 如果同一 shell/session 中之前加载过另一个 env 文件,身份可能以不安全的方式持续存在,除非你有意切换并验证
这种回退/共享认证行为对人类用户很方便,但在多 Agent 自动化中,可能导致错误的 GitLab 账户发布评论、创建 MR 或批准工作。
Required pre-flight before any GitLab write
任何 GitLab 写入前必需的预检
Run this immediately before any GitLab write, including , review submission or approval, thread replies, and any /// call:
glab mr noteglab apiPOSTPATCHPUTDELETEbash
glab auth status --hostname "$GITLAB_HOST"
glab api --hostname "$GITLAB_HOST" userThis assumes the target actor env file set for the exact GitLab instance you intend to modify. Do not write until both commands clearly show the intended visible actor on that host.
GITLAB_HOST在任何 GitLab 写入之前立即运行以下命令,包括 、review submission or approval、thread replies,以及任何 /// 调用:
glab mr noteglab apiPOSTPATCHPUTDELETEbash
glab auth status --hostname "$GITLAB_HOST"
glab api --hostname "$GITLAB_HOST" user这假定目标 actor 的 env 文件已为准确要修改的 GitLab 实例设置 。在两条命令都明确显示目标主机上的预期可见 actor 之前,不要执行写入。
GITLAB_HOSTWrong-identity remediation
错误身份修复
If a comment or reply was posted under the wrong identity:
- Stop posting.
- Delete the mistaken comment or reply if cleanup is needed.
- or start a fresh shell.
unset GITLAB_TOKEN GITLAB_ACCESS_TOKEN OAUTH_TOKEN GITLAB_HOST - Source the correct env file with .
set -a; source ...; set +a - Rerun and
glab auth status --hostname "$GITLAB_HOST".glab api --hostname "$GITLAB_HOST" user - Repost under the correct actor.
- Verify the thread no longer shows the wrong visible author for the replacement message.
If the wrong-identity write changed state beyond a comment or reply, re-auth as above and then use the matching GitLab reversal for that write under the correct actor and host, such as unapproving an MR or issuing the compensating mutation for the exact resource that was changed.
glab api --hostname "$GITLAB_HOST"如果评论或回复使用了错误身份发布:
- 停止发布。
- 如需清理,删除错误的评论或回复。
- 执行 或启动新的 shell。
unset GITLAB_TOKEN GITLAB_ACCESS_TOKEN OAUTH_TOKEN GITLAB_HOST - 使用 加载正确的 env 文件。
set -a; source ...; set +a - 重新运行 和
glab auth status --hostname "$GITLAB_HOST"。glab api --hostname "$GITLAB_HOST" user - 使用正确的 actor 重新发布。
- 验证讨论线程中不再显示替换消息的错误可见作者。
如果错误身份的写入造成了评论或回复之外的状态变更,请按上述方式重新认证,然后在正确的 actor 和主机下使用与该写入对应的 GitLab 回滚操作,例如取消批准 MR,或针对已更改的确切资源执行相应的 补偿性 mutation。
glab api --hostname "$GITLAB_HOST"Switching accounts/instances
切换账户/实例
-
Logout from current:bash
glab auth logout -
Login to new instance:bash
glab auth login --hostname gitlab.company.com -
Verify:bash
glab auth status --hostname gitlab.company.com
-
退出当前账户:bash
glab auth logout -
登录新实例:bash
glab auth login --hostname gitlab.company.com -
验证:bash
glab auth status --hostname gitlab.company.com
Docker registry access
Docker Registry 访问
-
Configure Docker helper:bash
glab auth configure-docker -
Verify Docker can authenticate:bash
docker login registry.gitlab.com -
Pull private images:bash
docker pull registry.gitlab.com/group/project/image:tag
configure-dockerdocker logindocker logout <domain>${DOCKER_CONFIG:-$HOME/.docker}/config.jsonglab normally installs the helper script beside the glab binary. If that directory is not writable, it falls back to , then another writable directory already on ; if the chosen directory is not on , follow the reported path instruction before testing Docker. Do not make the glab installation directory broadly writable just to place the helper there.
~/.local/binPATHPATH-
配置 Docker helper:bash
glab auth configure-docker -
验证 Docker 能否完成身份认证:bash
docker login registry.gitlab.com -
拉取私有镜像:bash
docker pull registry.gitlab.com/group/project/image:tag
configure-dockerdocker logindocker logout <domain>该文件为 ;请私下与操作者确认目标位置。备份应保持私密并置于仓库之外。不要在 Agent 输出、日志或聊天中显示该文件或原始 helper 值。在操作者明确批准迁移前,保留当前 helper。
${DOCKER_CONFIG:-$HOME/.docker}/config.jsonglab 通常会在 glab binary 旁安装 helper script。如果该目录不可写,则回退到 ,随后再回退到 PATH 中另一个可写目录;如果所选目录不在 PATH 中,请按照报告的路径说明操作,然后再测试 Docker。不要为了放置 helper 而将 glab 安装目录设置为全局可写。
~/.local/binTroubleshooting
故障排查
"401 Unauthorized" errors:
- Check status:
glab auth status - Verify token hasn't expired (check GitLab settings)
- Re-authenticate:
glab auth login
Re-login still looks stuck after changing auth method:
- If you switched from browser/OAuth login to token-based login and still appears to use stale stored credentials, run
glabagain instead of assuming the config must be edited manually.glab auth login - After re-login, verify with before retrying the failing command.
glab auth status
Env-token auth failures:
- If ,
GITLAB_TOKEN, orGITLAB_ACCESS_TOKENis exported, it overrides stored credentials only for trusted hosts (see above).OAUTH_TOKEN - and
GITLAB_TOKENare treated as personal access tokens independently of a stored OAuth profile, so a temporary PAT does not inherit or refresh saved OAuth state.GITLAB_ACCESS_TOKEN - If the host is configured for OAuth but an environment variable contains an OAuth access token, set ; otherwise glab sends the environment token as a personal access token.
GLAB_IS_OAUTH2=truereports this scheme mismatch after a 401.glab auth status - If auth suddenly fails, check whether an env token is being picked up before assuming your saved login is broken. and
glab auth loginwarn when this precedence applies.glab auth status - Run to distinguish a wrapper that intentionally injects a token (for example, a 1Password shell plugin alias) from a plain executable path. A wrapper can be expected and need no action; a plain path means the token came from the shell profile, current environment, or CI variables.
type glab - These failures can affect both read operations and writes, not just write pre-flight checks.
- Verify the active actor and token path with and
glab auth statusbefore any GitLab write.glab api user - In multi-agent shells, deliberately re-source the intended env file with before retrying.
set -a; source ...; set +a
Self-managed OAuth URL or refresh problems:
- Re-authenticate with the full configured host/subfolder; browser OAuth includes the configured subfolder in its authorization URL.
- OAuth token refresh also uses the configured subfolder; verify before assuming the token endpoint is at the host root.
glab config get subfolder --host <host> - A stored OAuth token inside the five-minute expiry grace period is proactively refreshed when credentials can be saved.
- A re-authentication response that omits a replacement refresh token preserves the existing refresh token instead of clearing it.
- If refresh fails with , re-run
invalid_grant; a revoked/expired OAuth grant or an earlier failed credential save can leave stored OAuth credentials stale.glab auth login - If OAuth refresh fails inside a sandbox with a credential-save error, grant write access to and re-authenticate. Retrying the same stale token normally will not repair the saved credential.
glab config path --dir - Docker and other helpers skip OAuth refresh for hosts authenticated with personal access tokens; check the token type before debugging OAuth state.
Multiple instances:
- Use flag to specify instance
--hostname - Each instance maintains separate auth
<a id="docker-helper-diagnostic"></a>
Docker authentication fails:
- Re-run:
glab auth configure-docker - Check only the intended registry's helper with the read-only diagnostic below
(requires Python 3 and a Bash-compatible shell). Replace with one non-empty exact registry key. It respects
registry.gitlab.com, falling back toDOCKER_CONFIGwhen unset or empty. Never print the full config: it can contain credentials for unrelated registries.$HOME/.docker - If Python 3 or a compatible shell is unavailable (including PowerShell/cmd-only
hosts), stop this optional diagnostic. Do not fall back to displaying the file,
a raw selected value, or credential-helper output. Ask the operator to inspect
the selected registry privately and report only ,
glab-cli,glab, ornot configured. Do not install tools or change configuration merely to run this check without operator approval.different helper configured
bash
python3 - registry.gitlab.com <<'PY'
import json
import os
import sys
from pathlib import Path
if len(sys.argv) != 2 or not sys.argv[1]:
sys.exit("Usage: pass one registry key.")
config_dir = os.environ.get("DOCKER_CONFIG") or str(Path.home() / ".docker")
try:
with (Path(config_dir) / "config.json").open(encoding="utf-8") as config_file:
contents = config_file.read()
config = json.loads(contents) if contents.strip(" \t\r\n") else {}
if not isinstance(config, dict):
raise ValueError
helpers = config.get("credHelpers")
if helpers is None:
helpers = {}
if not isinstance(helpers, dict):
raise ValueError
helper = helpers.get(sys.argv[1], "")
if helper is None:
helper = ""
if not isinstance(helper, str):
raise ValueError
except FileNotFoundError:
sys.exit("Docker config is missing.")
except (OSError, ValueError, RecursionError):
# Do not include exception details: they can contain config data or paths.
sys.exit("Docker config is unreadable or invalid.")
if helper == "glab-cli":
print("Selected registry credential helper: glab-cli")
elif helper == "glab":
print("Selected registry credential helper: glab")
elif not helper:
print("Selected registry credential helper: not configured")
else:
print("Selected registry credential helper: different helper configured")
PYThe diagnostic reports fixed statuses for (auth configure-docker),
(Artifact Registry), another helper, or no per-registry helper. It never
invokes a credential helper or prints raw configuration values, even values
containing only letters, digits, or punctuation. A different helper is not
permission to replace it: keep it and ask the operator to review the conflict
privately before approving migration. Artifact Registry's helper is a
separate integration; see .
Empty or JSON-whitespace-only files, null maps, and null/empty
selected helpers report . Missing/unreadable files, invalid
shapes, and malformed JSON produce a fixed error and exit 1. The diagnostic
deliberately rejects trailing data and non-object roots even where Docker's
loader tolerates them; this is a conservative inspection boundary, not a claim
that Docker cannot load the file. Stop and ask for private operator review on
error, rather than automatically repairing it. Missing, empty, or extra registry
arguments produce a fixed usage error before any config read.
A successful check exits 0 even when the helper is absent or different; this is
configuration inspection, not an authentication test. Global credential stores
and legacy entries are deliberately not reported.
glab-cliglabglabglab-artifact-registrycredHelpersnot configuredauths“401 Unauthorized” 错误:
- 检查状态:
glab auth status - 验证 token 未过期(检查 GitLab 设置)
- 重新认证:
glab auth login
更改身份验证方式后,重新登录似乎仍卡住:
- 如果从浏览器/OAuth 登录切换到基于 token 的登录后,glab 似乎仍在使用过期的存储凭据,请再次运行 ,不要直接假定必须手动编辑配置。
glab auth login - 重新登录后,先使用 验证,再重试失败的命令。
glab auth status
环境 token 身份认证失败:
- 如果导出了 、
GITLAB_TOKEN或GITLAB_ACCESS_TOKEN,它仅对受信任主机覆盖已存储的凭据(见上文)。OAUTH_TOKEN - 和
GITLAB_TOKEN会被独立视为 personal access token,因此临时 PAT 不会继承或刷新已保存的 OAuth 状态。GITLAB_ACCESS_TOKEN - 如果主机配置为 OAuth,但环境变量中包含 OAuth access token,请设置 ;否则 glab 会将环境 token 作为 personal access token 发送。发生 401 后,
GLAB_IS_OAUTH2=true会报告此方案不匹配。glab auth status - 如果身份认证突然失败,请先检查是否选中了环境 token,不要直接假定已保存的登录状态已损坏。和
glab auth login会在这种优先级生效时发出警告。glab auth status - 运行 ,以区分有意注入 token 的 wrapper(例如 1Password shell plugin alias)与普通可执行文件路径。Wrapper 的行为可能是预期且无需处理;如果显示普通路径,则说明 token 来自 shell profile、当前环境或 CI 变量。
type glab - 这些失败不仅会影响写入前的检查,也会影响读取操作和写入操作。
- 在任何 GitLab 写入前,使用 和
glab auth status验证当前 actor 和 token 来源。glab api user - 在多 Agent shell 中,重试前应有意使用 重新加载目标 env 文件。
set -a; source ...; set +a
Self-Managed OAuth URL 或刷新问题:
- 使用完整配置的 host/subfolder 重新认证;浏览器 OAuth 的授权 URL 包含配置的 subfolder。
- OAuth token 刷新也会使用配置的 subfolder;在假定 token endpoint 位于主机根目录之前,请运行 验证。
glab config get subfolder --host <host> - 处于五分钟过期宽限期内的已存储 OAuth token,会在凭据可保存时主动刷新。
- 如果重新认证响应未提供新的 refresh token,则保留现有 refresh token,而不是将其清除。
- 如果刷新因 失败,请重新运行
invalid_grant;授权被撤销或过期,以及之前保存凭据失败,都可能使已存储的 OAuth 凭据失效。glab auth login - 如果在 sandbox 中刷新 OAuth 时出现凭据保存错误,请授予 glab 对 的写入权限并重新认证。重试同一个过期 token 通常无法修复已保存的凭据。
glab config path --dir - Docker 和其他 helper 会跳过使用 personal access token 认证的主机上的 OAuth 刷新;排查 OAuth 状态前,请先检查 token 类型。
多个实例:
- 使用 标志指定实例
--hostname - 每个实例分别维护独立的身份认证状态
<a id="docker-helper-diagnostic"></a>
Docker 身份认证失败:
- 重新运行:
glab auth configure-docker - 仅使用下方只读诊断检查目标 registry 的 helper(需要 Python 3 和兼容 Bash 的 shell)。将 替换为一个非空的准确 registry key。 该诊断遵循
registry.gitlab.com,未设置或为空时回退到DOCKER_CONFIG。 绝不打印完整配置:其中可能包含无关 registry 的凭据。$HOME/.docker - 如果 Python 3 或兼容 shell 不可用(包括仅支持 PowerShell/cmd 的主机),请停止此可选诊断。不要回退为显示文件、原始选定值或 credential-helper 输出。请让操作者私下检查目标 registry,并仅报告 、
glab-cli、glab或not configured。未经操作者批准,不要安装工具或更改配置来执行此检查。different helper configured
bash
python3 - registry.gitlab.com <<'PY'
import json
import os
import sys
from pathlib import Path
if len(sys.argv) != 2 or not sys.argv[1]:
sys.exit("Usage: pass one registry key.")
config_dir = os.environ.get("DOCKER_CONFIG") or str(Path.home() / ".docker")
try:
with (Path(config_dir) / "config.json").open(encoding="utf-8") as config_file:
contents = config_file.read()
config = json.loads(contents) if contents.strip(" \t\r\n") else {}
if not isinstance(config, dict):
raise ValueError
helpers = config.get("credHelpers")
if helpers is None:
helpers = {}
if not isinstance(helpers, dict):
raise ValueError
helper = helpers.get(sys.argv[1], "")
if helper is None:
helper = ""
if not isinstance(helper, str):
raise ValueError
except FileNotFoundError:
sys.exit("Docker config is missing.")
except (OSError, ValueError, RecursionError):
# Do not include exception details: they can contain config data or paths.
sys.exit("Docker config is unreadable or invalid.")
if helper == "glab-cli":
print("Selected registry credential helper: glab-cli")
elif helper == "glab":
print("Selected registry credential helper: glab")
elif not helper:
print("Selected registry credential helper: not configured")
else:
print("Selected registry credential helper: different helper configured")
PY该诊断会报告固定状态:(由 配置)、(Artifact Registry)、其他 helper,或未配置按 registry 的 helper。它绝不会调用 credential helper,也不会打印原始配置值,即使这些值仅包含字母、数字或标点。存在其他 helper 并不代表可以替换它:应保留该 helper,并请操作者私下审查冲突,之后再批准迁移。Artifact Registry 的 helper 是独立集成;请参阅 。
glab-cliglab auth configure-dockerglabglabglab-artifact-registry空文件或仅含 JSON 空白字符的文件、为 null 的 map,以及为 null 或空值的选定 helper,都会报告 。文件缺失或不可读、结构无效及 JSON 格式错误会产生固定错误并以状态码 1 退出。该诊断有意拒绝尾随数据和非对象根节点,即使 Docker 的加载器可以容忍这些情况;这是保守的检查边界,并不表示 Docker 无法加载该文件。出现错误时,请停止操作并请操作者私下审查,不要自动修复。传入缺失、为空或额外的 registry 参数时,会在读取配置之前产生固定用法错误。
credHelpersnot configured成功检查即使发现 helper 缺失或不同,也会以状态码 0 退出;这是配置检查,而不是身份认证测试。有意不报告全局凭据存储和旧版 条目。
authsSubcommands
子命令
See references/commands.md for detailed flag documentation:
- - Authenticate with GitLab instance
login - - Log out of GitLab instance
logout - - View authentication status
status - - Configure Docker to use GitLab registry
configure-docker - - Docker credential helper
docker-helper - - Generate DPoP token
dpop-gen
有关详细标志文档,请参阅 references/commands.md:
- - 对 GitLab 实例进行身份认证
login - - 退出 GitLab 实例
logout - - 查看身份认证状态
status - - 配置 Docker 使用 GitLab Registry
configure-docker - - Docker credential helper
docker-helper - - 生成 DPoP token
dpop-gen
Related Skills
相关 Skills
Initial setup:
- After authentication, see to set CLI defaults
glab-config - See for SSH key management
glab-ssh-key - See for commit signing setup
glab-gpg-key
Repository operations:
- See for cloning repositories
glab-repo - Authentication required before first clone/push
初始设置:
- 完成身份认证后,请参阅 了解如何设置 CLI 默认值
glab-config - 请参阅 了解 SSH 密钥管理
glab-ssh-key - 请参阅 了解 commit 签名设置
glab-gpg-key
仓库操作:
- 请参阅 了解如何克隆仓库
glab-repo - 首次 clone/push 前需要完成身份认证