authentication-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Table of Contents

目录

Authentication Patterns

认证模式

Overview

概述

Common authentication patterns for integrating with external services. Provides consistent approaches to credential management, verification, and error handling.
与外部服务集成时的常见认证模式,提供了凭据管理、验证和错误处理的统一方法。

When To Use

适用场景

  • Integrating with external APIs
  • Need credential verification
  • Managing multiple auth methods
  • Handling auth failures gracefully
  • 与外部API集成
  • 需要凭据验证
  • 管理多种认证方式
  • 优雅处理认证失败

When NOT To Use

不适用场景

  • Project doesn't use the leyline infrastructure patterns
  • Simple scripts without service architecture needs
  • 项目未采用leyline基础设施模式
  • 无服务架构需求的简单脚本

Authentication Methods

认证方式

MethodBest ForEnvironment Variable
API KeySimple integrations
{SERVICE}_API_KEY
OAuthUser-authenticatedBrowser-based flow
TokenSession-based
{SERVICE}_TOKEN
NonePublic APIsN/A
方式适用场景环境变量
API密钥简单集成
{SERVICE}_API_KEY
OAuth用户认证场景基于浏览器的流程
令牌基于会话的场景
{SERVICE}_TOKEN
公开APIN/A

Quick Start

快速开始

Verify Authentication

验证认证

python
from leyline.auth import verify_auth, AuthMethod
python
from leyline.auth import verify_auth, AuthMethod

API Key verification

API Key verification

status = verify_auth( service="gemini", method=AuthMethod.API_KEY, env_var="GEMINI_API_KEY" )
if not status.authenticated: print(f"Auth failed: {status.message}") print(f"Action: {status.suggested_action}")
**Verification:** Run the command with `--help` flag to verify availability.
status = verify_auth( service="gemini", method=AuthMethod.API_KEY, env_var="GEMINI_API_KEY" )
if not status.authenticated: print(f"Auth failed: {status.message}") print(f"Action: {status.suggested_action}")
**验证:** 运行带`--help`参数的命令以确认可用。

Smoke Test

冒烟测试

python
def verify_with_smoke_test(service: str) -> bool:
    """Verify auth with simple request."""
    result = execute_simple_request(service, "ping")
    return result.success
Verification: Run
pytest -v
to verify tests pass.
python
def verify_with_smoke_test(service: str) -> bool:
    """Verify auth with simple request."""
    result = execute_simple_request(service, "ping")
    return result.success
验证: 运行
pytest -v
以确认测试通过。

Standard Flow

标准流程

Step 1: Check Environment

步骤1:检查环境

python
def check_credentials(service: str, env_var: str) -> bool:
    value = os.getenv(env_var)
    if not value:
        print(f"Missing {env_var}")
        return False
    return True
Verification: Run the command with
--help
flag to verify availability.
python
def check_credentials(service: str, env_var: str) -> bool:
    value = os.getenv(env_var)
    if not value:
        print(f"Missing {env_var}")
        return False
    return True
验证: 运行带
--help
参数的命令以确认可用。

Step 2: Verify with Service

步骤2:通过服务验证

python
def verify_with_service(service: str) -> AuthStatus:
    result = subprocess.run(
        [service, "auth", "status"],
        capture_output=True
    )
    return AuthStatus(
        authenticated=(result.returncode == 0),
        message=result.stdout.decode()
    )
Verification: Run the command with
--help
flag to verify availability.
python
def verify_with_service(service: str) -> AuthStatus:
    result = subprocess.run(
        [service, "auth", "status"],
        capture_output=True
    )
    return AuthStatus(
        authenticated=(result.returncode == 0),
        message=result.stdout.decode()
    )
验证: 运行带
--help
参数的命令以确认可用。

Step 3: Handle Failures

步骤3:处理失败

python
def handle_auth_failure(service: str, method: AuthMethod) -> str:
    actions = {
        AuthMethod.API_KEY: f"Set {service.upper()}_API_KEY environment variable",
        AuthMethod.OAUTH: f"Run '{service} auth login' for browser auth",
        AuthMethod.TOKEN: f"Refresh token with '{service} token refresh'"
    }
    return actions[method]
Verification: Run the command with
--help
flag to verify availability.
python
def handle_auth_failure(service: str, method: AuthMethod) -> str:
    actions = {
        AuthMethod.API_KEY: f"Set {service.upper()}_API_KEY environment variable",
        AuthMethod.OAUTH: f"Run '{service} auth login' for browser auth",
        AuthMethod.TOKEN: f"Refresh token with '{service} token refresh'"
    }
    return actions[method]
验证: 运行带
--help
参数的命令以确认可用。

Integration Pattern

集成模式

yaml
undefined
yaml
undefined

In your skill's frontmatter

In your skill's frontmatter

dependencies: [leyline:authentication-patterns]
**Verification:** Run the command with `--help` flag to verify availability.
dependencies: [leyline:authentication-patterns]
**验证:** 运行带`--help`参数的命令以确认可用。

Interactive Authentication (Shell)

交互式认证(Shell)

For workflows requiring interactive authentication with token caching and session management:
bash
undefined
对于需要交互式认证、令牌缓存和会话管理的工作流:
bash
undefined

Source the interactive auth script

Source the interactive auth script

source plugins/leyline/scripts/interactive_auth.sh
source plugins/leyline/scripts/interactive_auth.sh

Ensure authentication before proceeding

Ensure authentication before proceeding

ensure_auth github || exit 1 ensure_auth gitlab || exit 1 ensure_auth aws || exit 1
ensure_auth github || exit 1 ensure_auth gitlab || exit 1 ensure_auth aws || exit 1

Continue with authenticated operations

Continue with authenticated operations

gh pr view 123 glab issue list aws s3 ls

**Features:**
- ✅ Interactive OAuth flows for GitHub, GitLab, AWS, and more
- ✅ Token caching (5-minute TTL)
- ✅ Session persistence (24-hour TTL)
- ✅ CI/CD compatible (auto-detects non-interactive environments)
- ✅ Multi-service support

See `modules/interactive-auth.md` for complete documentation.
gh pr view 123 glab issue list aws s3 ls

**特性:**
- ✅ 支持GitHub、GitLab、AWS等的交互式OAuth流程
- ✅ 令牌缓存(5分钟TTL)
- ✅ 会话持久化(24小时TTL)
- ✅ 兼容CI/CD(自动检测非交互式环境)
- ✅ 多服务支持

完整文档请参阅`modules/interactive-auth.md`。

Detailed Resources

详细资源

  • Auth Methods: See
    modules/auth-methods.md
    for method details
  • Verification: See
    modules/verification-patterns.md
    for testing patterns
  • Interactive: See
    modules/interactive-auth.md
    for shell-based auth flows
  • 认证方式: 查看
    modules/auth-methods.md
    获取方式详情
  • 验证: 查看
    modules/verification-patterns.md
    获取测试模式
  • 交互式认证: 查看
    modules/interactive-auth.md
    获取基于Shell的认证流程

Exit Criteria

退出标准

  • Credentials verified or clear failure message
  • Suggested action for auth failures
  • Smoke test confirms working auth
  • 凭据已验证或获取明确的失败信息
  • 提供认证失败的建议操作
  • 冒烟测试确认认证正常工作

Troubleshooting

故障排除

Common Issues

常见问题

Command not found Ensure all dependencies are installed and in PATH
Permission errors Check file permissions and run with appropriate privileges
Unexpected behavior Enable verbose logging with
--verbose
flag
命令未找到 确保所有依赖已安装且位于PATH中
权限错误 检查文件权限并使用适当权限运行
意外行为 使用
--verbose
参数启用详细日志