111k

Authentication

使用认证保护你的注册库,以支持私有和个性化组件。

认证允许你运行私有注册库、控制谁可以访问你的组件,并为不同团队或用户提供不同内容。本指南展示了常见的认证模式以及它们的设置方法。

认证可支持以下用例:

  • 私有组件:保护你的业务逻辑和内部组件安全
  • 团队专属资源:为不同团队提供不同组件
  • 访问控制:限制谁可以查看敏感或实验性组件
  • 使用分析:查看组织内谁在使用哪些组件
  • 许可管理:控制谁可以获得付费或授权组件

常见认证模式

基于 Token 的认证

最常见的方法是使用 Bearer token 或 API key:

components.json
{
  "registries": {
    "@private": {
      "url": "https://registry.company.com/{name}.json",
      "headers": {
        "Authorization": "Bearer ${REGISTRY_TOKEN}"
      }
    }
  }
}

将你的 token 设置在环境变量中:

.env.local
REGISTRY_TOKEN=your_secret_token_here

API Key 认证

有些注册库会在请求头中使用 API key:

components.json
{
  "registries": {
    "@company": {
      "url": "https://api.company.com/registry/{name}.json",
      "headers": {
        "X-API-Key": "${API_KEY}",
        "X-Workspace-Id": "${WORKSPACE_ID}"
      }
    }
  }
}

查询参数认证

对于更简单的设置,可以使用查询参数:

components.json
{
  "registries": {
    "@internal": {
      "url": "https://registry.company.com/{name}.json",
      "params": {
        "token": "${ACCESS_TOKEN}"
      }
    }
  }
}

这会生成:https://registry.company.com/button.json?token=your_token

服务端实现

下面介绍如何为你的注册库服务端添加认证:

Next.js API 路由示例

app/api/registry/[name]/route.ts
import { NextRequest, NextResponse } from "next/server"
 
export async function GET(
  request: NextRequest,
  { params }: { params: { name: string } }
) {
  // 从 Authorization 头中获取 token。
  const authHeader = request.headers.get("authorization")
  const token = authHeader?.replace("Bearer ", "")
 
  // 或从查询参数中获取。
  const queryToken = request.nextUrl.searchParams.get("token")
 
  // 检查 token 是否有效。
  if (!isValidToken(token || queryToken)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
  }
 
  // 检查 token 是否可以访问这个组件。
  if (!hasAccessToComponent(token, params.name)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 })
  }
 
  // 返回组件。
  const component = await getComponent(params.name)
  return NextResponse.json(component)
}
 
function isValidToken(token: string | null) {
  // 在这里添加你的 token 校验逻辑。
  // 可以检查数据库、JWT 验证等。
  return token === process.env.VALID_TOKEN
}
 
function hasAccessToComponent(token: string, componentName: string) {
  // 在这里添加基于角色的访问控制。
  // 检查 token 是否可以访问特定组件。
  return true // 你的逻辑在这里。
}

Express.js 示例

server.js
app.get("/registry/:name.json", (req, res) => {
  const token = req.headers.authorization?.replace("Bearer ", "")
 
  if (!isValidToken(token)) {
    return res.status(401).json({ error: "Unauthorized" })
  }
 
  const component = getComponent(req.params.name)
  if (!component) {
    return res.status(404).json({ error: "Component not found" })
  }
 
  res.json(component)
})

高级认证模式

基于团队的访问

为不同团队提供不同组件:

api/registry/route.ts
async function GET(request: NextRequest) {
  const token = extractToken(request)
  const team = await getTeamFromToken(token)
 
  // 获取该团队的组件。
  const components = await getComponentsForTeam(team)
  return NextResponse.json(components)
}

用户个性化注册库

根据用户偏好提供组件:

async function GET(request: NextRequest) {
  const user = await authenticateUser(request)
 
  // 获取用户的样式和框架偏好。
  const preferences = await getUserPreferences(user.id)
 
  // 获取个性化组件版本。
  const component = await getPersonalizedComponent(params.name, preferences)
 
  return NextResponse.json(component)
}

临时访问 Token

使用会过期的 token 以提高安全性:

interface TemporaryToken {
  token: string
  expiresAt: Date
  scope: string[]
}
 
async function validateTemporaryToken(token: string) {
  const tokenData = await getTokenData(token)
 
  if (!tokenData) return false
  if (new Date() > tokenData.expiresAt) return false
 
  return true
}

多注册库认证

借助 命名空间注册库,你可以为多个注册库设置不同的认证方式:

components.json
{
  "registries": {
    "@public": "https://public.company.com/{name}.json",
    "@internal": {
      "url": "https://internal.company.com/{name}.json",
      "headers": {
        "Authorization": "Bearer ${INTERNAL_TOKEN}"
      }
    },
    "@premium": {
      "url": "https://premium.company.com/{name}.json",
      "headers": {
        "X-License-Key": "${LICENSE_KEY}"
      }
    }
  }
}

这可以让你:

  • 混合使用公共和私有注册库
  • 为每个注册库使用不同的认证方式
  • 按访问级别组织组件

安全最佳实践

使用环境变量

永远不要把 token 提交到版本控制中。始终使用环境变量:

.env.local
REGISTRY_TOKEN=your_secret_token_here
API_KEY=your_api_key_here

然后在 components.json 中引用它们:

{
  "registries": {
    "@private": {
      "url": "https://registry.company.com/{name}.json",
      "headers": {
        "Authorization": "Bearer ${REGISTRY_TOKEN}"
      }
    }
  }
}

使用 HTTPS

始终为注册库使用 HTTPS URL,以保护传输中的 token:

{
  "@secure": "https://registry.company.com/{name}.json", // ✅
  "@insecure": "http://registry.company.com/{name}.json" // ❌
}

添加限流

保护你的注册库免受滥用:

import rateLimit from "express-rate-limit"
 
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 分钟
  max: 100, // 限制每个 IP 在 windowMs 内最多 100 个请求
})
 
app.use("/registry", limiter)

定期轮换 Token

定期更换访问 token:

// 创建一个带过期时间的新 token。
function generateToken() {
  const token = crypto.randomBytes(32).toString("hex")
  const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) // 30 天。
 
  return { token, expiresAt }
}

记录访问日志

记录注册库访问情况,用于安全和分析:

async function logAccess(request: Request, component: string, userId: string) {
  await db.accessLog.create({
    timestamp: new Date(),
    userId,
    component,
    ip: request.ip,
    userAgent: request.headers["user-agent"],
  })
}

测试认证

在本地测试你的认证注册库:

# 使用 curl 测试。
curl -H "Authorization: Bearer your_token" \
  https://registry.company.com/button.json
 
# 使用 CLI 测试。
REGISTRY_TOKEN=your_token npx shadcn@latest add @private/button

错误处理

shadcn CLI 会优雅处理认证错误:

  • 401 Unauthorized:Token 无效或缺失
  • 403 Forbidden:Token 没有该资源的权限
  • 429 Too Many Requests:超出限流

自定义错误消息

你的注册库服务端可以在响应体中返回自定义错误消息,CLI 会把它们显示给用户:

// 注册库服务端返回自定义错误
return NextResponse.json(
  {
    error: "Unauthorized",
    message: "你的订阅已过期。请前往 company.com/billing 续订",
  },
  { status: 403 }
)

用户将看到:

你的订阅已过期。请前往 company.com/billing 续订

这有助于提供与上下文相关的指引:

// 针对不同场景返回不同的错误消息
if (!token) {
  return NextResponse.json(
    {
      error: "Unauthorized",
      message: "需要进行身份验证。请在 .env.local 文件中设置 REGISTRY_TOKEN",
    },
    { status: 401 }
  )
}
 
if (isExpiredToken(token)) {
  return NextResponse.json(
    {
      error: "Unauthorized",
      message: "Token 已过期。请前往 company.com/tokens 申请新 token",
    },
    { status: 401 }
  )
}
 
if (!hasTeamAccess(token, component)) {
  return NextResponse.json(
    {
      error: "Forbidden",
      message: `组件 '${component}' 仅限 Design 团队访问`,
    },
    { status: 403 }
  )
}

下一步

要为多个注册库和高级模式设置认证,请查看 Namespaced Registries 文档,其中涵盖:

  • 配置多个带认证的注册库
  • 为每个命名空间使用不同的认证方式
  • 跨注册库依赖解析
  • 高级认证模式