设备授权

RFC 8628 CLI 智能电视 物联网

设备授权插件实现了 OAuth 2.0 设备授权许可(RFC 8628),为输入能力有限的设备(如智能电视、CLI 应用程序、物联网设备和游戏主机)提供身份验证支持。

试用体验

您可以使用 Better Auth CLI 立即测试设备授权流程:

npx @better-auth/cli login

这将演示完整的设备授权流程:

  1. 从 Better Auth 演示服务器请求设备代码
  2. 显示需要您输入的用户代码
  3. 打开浏览器访问验证页面
  4. 轮询检查授权是否完成

CLI 登录命令是一个演示功能,它连接到 Better Auth 演示服务器,以展示设备授权流程的实际运行情况。

安装步骤

将插件添加到认证配置

将设备授权插件添加到您的服务器配置中。

auth.ts
import { betterAuth } from "better-auth";
import { deviceAuthorization } from "better-auth/plugins"; 

export const auth = betterAuth({
  // ... 其他配置
  plugins: [ 
    deviceAuthorization({ 
      // 可选配置
      expiresIn: "30m", // 设备码过期时间
      interval: "5s",    // 最小轮询间隔
    }), 
  ], 
});

迁移数据库

运行迁移或生成模式以将必要的表添加到数据库中。

npx @better-auth/cli migrate
npx @better-auth/cli generate

请参阅模式部分以手动添加字段。

添加客户端插件

将设备授权插件添加到您的客户端。

auth-client.ts
import { createAuthClient } from "better-auth/client";
import { deviceAuthorizationClient } from "better-auth/client/plugins"; 

export const authClient = createAuthClient({
  plugins: [ 
    deviceAuthorizationClient(), 
  ], 
});

工作原理

设备授权流程遵循以下步骤:

  1. 设备请求授权码:设备向授权服务器请求设备码和用户码
  2. 用户授权:用户访问验证 URL 并输入用户码
  3. 设备轮询令牌:设备轮询服务器直到用户完成授权
  4. 访问授权:一旦授权成功,设备将收到访问令牌

基本用法

请求设备授权

要启动设备授权,使用客户端 ID 调用 device.code

POST
/device/code
const { data, error } = await authClient.device.code({    client_id, // required    scope,});
属性描述类型
client_id
OAuth 客户端标识符
string;
scope?
请求的权限范围列表(空格分隔,可选)
string;

使用示例:

const { data } = await authClient.device.code({
  client_id: "your-client-id",
  scope: "openid profile email",
});

if (data) {
  console.log(`请访问: ${data.verification_uri}`);
  console.log(`并输入验证码: ${data.user_code}`);
}

轮询获取令牌

在显示用户代码后,轮询获取访问令牌:

POST
/device/token
const { data, error } = await authClient.device.token({    grant_type, // required    device_code, // required    client_id, // required});
属性描述类型
grant_type
必须为 "urn:ietf:params:oauth:grant-type:device_code"
string;
device_code
来自初始请求的设备代码
string;
client_id
OAuth 客户端标识符
string;

轮询实现示例:

let pollingInterval = 5; // 从 5 秒开始
const pollForToken = async () => {
  const { data, error } = await authClient.device.token({
    grant_type: "urn:ietf:params:oauth:grant-type:device_code",
    device_code,
    client_id: yourClientId,
    fetchOptions: {
      headers: {
        "user-agent": `My CLI`,
      },
    },
  });

  if (data?.access_token) {
    console.log("授权成功!");
  } else if (error) {
    switch (error.error) {
      case "authorization_pending":
        // 继续轮询
        break;
      case "slow_down":
        pollingInterval += 5;
        break;
      case "access_denied":
        console.error("用户拒绝了访问");
        return;
      case "expired_token":
        console.error("设备代码已过期,请重试");
        return;
      default:
        console.error(`错误:${error.error_description}`);
        return;
    }
    setTimeout(pollForToken, pollingInterval * 1000);
  }
};

pollForToken();

用户授权流程

用户授权流程需要两个步骤:

  1. 代码验证:检查输入的用户代码是否有效
  2. 授权:用户必须通过身份验证才能批准/拒绝设备

用户必须先通过身份验证,然后才能批准或拒绝设备授权请求。如果未通过身份验证,请将其重定向到登录页面并附带返回 URL。

创建一个页面,用户可以在其中输入他们的代码:

app/device/page.tsx
export default function DeviceAuthorizationPage() {
  const [userCode, setUserCode] = useState("");
  const [error, setError] = useState(null);
  
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    try {
      // 格式化代码:移除破折号并转换为大写
      const formattedCode = userCode.trim().replace(/-/g, "").toUpperCase();

      // 使用 GET /device 端点检查代码是否有效
      const response = await authClient.device.deviceVerify({
        query: { user_code: formattedCode },
      });
      
      if (response.data) {
        // 重定向到批准页面
        window.location.href = `/device/approve?user_code=${formattedCode}`;
      }
    } catch (err) {
      setError("无效或已过期的代码");
    }
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={userCode}
        onChange={(e) => setUserCode(e.target.value)}
        placeholder="输入设备代码(例如:ABCD-1234)"
        maxLength={12}
      />
      <button type="submit">继续</button>
      {error && <p>{error}</p>}
    </form>
  );
}

批准或拒绝设备

用户必须通过身份验证才能批准或拒绝设备授权请求:

批准设备

POST
/device/approve
const { data, error } = await authClient.device.approve({    userCode, // required});
属性描述类型
userCode
要批准的用户代码
string;

拒绝设备

POST
/device/deny
const { data, error } = await authClient.device.deny({    userCode, // required});
属性描述类型
userCode
要拒绝的用户代码
string;

示例批准页面

app/device/approve/page.tsx
export default function DeviceApprovalPage() {
  const { user } = useAuth(); // 必须已认证
  const searchParams = useSearchParams();
  const userCode = searchParams.get("userCode");
  const [isProcessing, setIsProcessing] = useState(false);
  
  const handleApprove = async () => {
    setIsProcessing(true);
    try {
      await authClient.device.deviceApprove({
        userCode: userCode,
      });
      // 显示成功消息
      alert("设备批准成功!");
      window.location.href = "/";
    } catch (error) {
      alert("批准设备失败");
    }
    setIsProcessing(false);
  };
  
  const handleDeny = async () => {
    setIsProcessing(true);
    try {
      await authClient.device.deviceDeny({
        userCode: userCode,
      });
      alert("设备已拒绝");
      window.location.href = "/";
    } catch (error) {
      alert("拒绝设备失败");
    }
    setIsProcessing(false);
  };

  if (!user) {
    // 如果未认证,重定向到登录页面
    window.location.href = `/login?redirect=/device/approve?user_code=${userCode}`;
    return null;
  }
  
  return (
    <div>
      <h2>设备授权请求</h2>
      <p>一个设备正在请求访问您的账户。</p>
      <p>代码:{userCode}</p>
      
      <button onClick={handleApprove} disabled={isProcessing}>
        批准
      </button>
      <button onClick={handleDeny} disabled={isProcessing}>
        拒绝
      </button>
    </div>
  );
}

高级配置

客户端验证

您可以验证客户端 ID,确保只有经过授权的应用程序可以使用设备流程:

deviceAuthorization({
  validateClient: async (clientId) => {
    // 检查客户端是否已授权
    const client = await db.oauth_clients.findOne({ id: clientId });
    return client && client.allowDeviceFlow;
  },
  
  onDeviceAuthRequest: async (clientId, scope) => {
    // 记录设备授权请求
    await logDeviceAuthRequest(clientId, scope);
  },
})

自定义代码生成

自定义设备和用户代码的生成方式:

deviceAuthorization({
  generateDeviceCode: async () => {
    // 自定义设备代码生成
    return crypto.randomBytes(32).toString("hex");
  },
  
  generateUserCode: async () => {
    // 自定义用户代码生成
    // 默认使用:ABCDEFGHJKLMNPQRSTUVWXYZ23456789
    // (排除 0, O, 1, I 以避免混淆)
    const charset = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
    let code = "";
    for (let i = 0; i < 8; i++) {
      code += charset[Math.floor(Math.random() * charset.length)];
    }
    return code;
  },
})

错误处理

设备流程定义了特定的错误代码:

错误代码描述
authorization_pending用户尚未批准(继续轮询)
slow_down轮询过于频繁(增加间隔时间)
expired_token设备代码已过期
access_denied用户拒绝了授权
invalid_grant无效的设备代码或客户端 ID

示例:CLI 应用程序

以下是一个基于实际演示的完整 CLI 应用程序示例:

cli-auth.ts
import { createAuthClient } from "better-auth/client";
import { deviceAuthorizationClient } from "better-auth/client/plugins";
import open from "open";

const authClient = createAuthClient({
  baseURL: "http://localhost:3000",
  plugins: [deviceAuthorizationClient()],
});

async function authenticateCLI() {
  console.log("🔐 Better Auth 设备授权演示");
  console.log("⏳ 正在请求设备授权...");
  
  try {
    // 请求设备代码
    const { data, error } = await authClient.device.code({
      client_id: "demo-cli",
      scope: "openid profile email",
    });
    
    if (error || !data) {
      console.error("❌ 错误:", error?.error_description);
      process.exit(1);
    }
    
    const {
      device_code,
      user_code,
      verification_uri,
      verification_uri_complete,
      interval = 5,
    } = data;
    
    console.log("\n📱 设备授权进行中");
    console.log(`请访问: ${verification_uri}`);
    console.log(`输入代码: ${user_code}\n`);
    
    // 使用完整 URL 打开浏览器
    const urlToOpen = verification_uri_complete || verification_uri;
    if (urlToOpen) {
      console.log("🌐 正在打开浏览器...");
      await open(urlToOpen);
    }
    
    console.log(`⏳ 等待授权中... (每 ${interval} 秒轮询一次)`);
    
    // 轮询获取令牌
    await pollForToken(device_code, interval);
  } catch (err) {
    console.error("❌ 错误:", err.message);
    process.exit(1);
  }
}

async function pollForToken(deviceCode: string, interval: number) {
  let pollingInterval = interval;
  
  return new Promise<void>((resolve) => {
    const poll = async () => {
      try {
        const { data, error } = await authClient.device.token({
          grant_type: "urn:ietf:params:oauth:grant-type:device_code",
          device_code: deviceCode,
          client_id: "demo-cli",
        });
        
        if (data?.access_token) {
          console.log("\n✅ 授权成功!");
          console.log("已收到访问令牌!");
          
          // 获取用户会话
          const { data: session } = await authClient.getSession({
            fetchOptions: {
              headers: {
                Authorization: `Bearer ${data.access_token}`,
              },
            },
          });
          
          console.log(`你好, ${session?.user?.name || "用户"}!`);
          resolve();
          process.exit(0);
        } else if (error) {
          switch (error.error) {
            case "authorization_pending":
              // 静默继续轮询
              break;
            case "slow_down":
              pollingInterval += 5;
              console.log(`⚠️  轮询间隔延长至 ${pollingInterval} 秒`);
              break;
            case "access_denied":
              console.error("❌ 用户拒绝了访问");
              process.exit(1);
              break;
            case "expired_token":
              console.error("❌ 设备代码已过期,请重试");
              process.exit(1);
              break;
            default:
              console.error("❌ 错误:", error.error_description);
              process.exit(1);
          }
        }
      } catch (err) {
        console.error("❌ 网络错误:", err.message);
        process.exit(1);
      }
      
      // 安排下一次轮询
      setTimeout(poll, pollingInterval * 1000);
    };
    
    // 开始轮询
    setTimeout(poll, pollingInterval * 1000);
  });
}

// 运行认证流程
authenticateCLI().catch((err) => {
  console.error("❌ 致命错误:", err);
  process.exit(1);
});

安全注意事项

  1. 频率限制:插件强制执行轮询间隔以防止滥用
  2. 代码过期:设备和用户代码在配置的时间后过期(默认:30分钟)
  3. 客户端验证:在生产环境中始终验证客户端ID以防止未经授权的访问
  4. 仅限HTTPS:在生产环境中始终使用HTTPS进行设备授权
  5. 用户代码格式:用户代码使用有限的字符集(排除外观相似的字符,如0/O、1/I)以减少输入错误
  6. 需要身份验证:用户必须先通过身份验证才能批准或拒绝设备请求

配置选项

服务端

expiresIn:设备代码的过期时间。默认:"30m"(30分钟)。

interval:最小轮询间隔。默认:"5s"(5秒)。

userCodeLength:用户代码的长度。默认:8

deviceCodeLength:设备代码的长度。默认:40

generateDeviceCode:生成设备代码的自定义函数。返回字符串或Promise<string>

generateUserCode:生成用户代码的自定义函数。返回字符串或Promise<string>

validateClient:验证客户端ID的函数。接收clientId并返回布尔值或Promise<boolean>

onDeviceAuthRequest:设备授权请求时调用的钩子函数。接收clientId和可选的scope参数。

客户端

无特定于客户端的配置选项。插件添加了以下方法:

  • device.code():请求设备和用户代码
  • device.token():轮询获取访问令牌
  • device.deviceVerify():验证用户代码有效性
  • device.deviceApprove():批准设备(需要身份验证)
  • device.deviceDeny():拒绝设备(需要身份验证)

数据库结构

该插件需要一个新表来存储设备授权数据。

表名:deviceCode

字段名称类型Key描述
idstring设备授权请求的唯一标识符
deviceCodestring-设备验证码
userCodestring-用于验证的用户友好代码
userIdstring批准/拒绝的用户ID
clientIdstringOAuth客户端标识符
scopestring请求的OAuth权限范围
statusstring-当前状态:pending(待处理)、approved(已批准)或denied(已拒绝)
expiresAtDate-设备码过期时间
lastPolledAtDate设备最后一次轮询状态的时间
pollingIntervalnumber轮询之间的最小间隔秒数
createdAtDate-请求创建时间
updatedAtDate-请求最后更新时间