authentication-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTable 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
认证方式
| Method | Best For | Environment Variable |
|---|---|---|
| API Key | Simple integrations | |
| OAuth | User-authenticated | Browser-based flow |
| Token | Session-based | |
| None | Public APIs | N/A |
| 方式 | 适用场景 | 环境变量 |
|---|---|---|
| API密钥 | 简单集成 | |
| OAuth | 用户认证场景 | 基于浏览器的流程 |
| 令牌 | 基于会话的场景 | |
| 无 | 公开API | N/A |
Quick Start
快速开始
Verify Authentication
验证认证
python
from leyline.auth import verify_auth, AuthMethodpython
from leyline.auth import verify_auth, AuthMethodAPI 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.successVerification: Run to verify tests pass.
pytest -vpython
def verify_with_smoke_test(service: str) -> bool:
"""Verify auth with simple request."""
result = execute_simple_request(service, "ping")
return result.success验证: 运行以确认测试通过。
pytest -vStandard 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 TrueVerification: Run the command with flag to verify availability.
--helppython
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验证: 运行带参数的命令以确认可用。
--helpStep 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 flag to verify availability.
--helppython
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()
)验证: 运行带参数的命令以确认可用。
--helpStep 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 flag to verify availability.
--helppython
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]验证: 运行带参数的命令以确认可用。
--helpIntegration Pattern
集成模式
yaml
undefinedyaml
undefinedIn 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
undefinedSource 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 for method details
modules/auth-methods.md - Verification: See for testing patterns
modules/verification-patterns.md - Interactive: See for shell-based auth flows
modules/interactive-auth.md
- 认证方式: 查看获取方式详情
modules/auth-methods.md - 验证: 查看获取测试模式
modules/verification-patterns.md - 交互式认证: 查看获取基于Shell的认证流程
modules/interactive-auth.md
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 flag
--verbose命令未找到
确保所有依赖已安装且位于PATH中
权限错误
检查文件权限并使用适当权限运行
意外行为
使用参数启用详细日志
--verbose