auth-nodejs-cloudbase by tencentcloudbase/skills
npx skills add https://github.com/tencentcloudbase/skills --skill auth-nodejs-cloudbase当任务涉及 CloudBase 项目中的服务器端身份验证或身份管理,且代码运行在 Node.js 环境中时,请使用此技能,例如:
以下情况请勿使用此技能:
@cloudbase/js-sdk 的前端 Web 登录/注册流程(使用 auth-web 技能处理,而非此 Node 技能)。当用户请求混合了前端和后端关注点时(例如,“构建一个 Web 登录页面和一个能识别用户的 Node API”),请分开处理:
当你加载此技能来处理任务时:
明确运行时环境和职责
询问用户:
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
确认 CloudBase 环境和 SDK
env – CloudBase 环境 ID@cloudbase/node-sdk。import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
从此文件中选取相关场景
getUserInfo 场景。getEndUserInfo 和 queryUserInfo 场景。createTicket 的自定义登录票据场景。getClientIP 场景。严格遵循 Node SDK API 结构
auth.* 方法和参数结构视为规范。如果你对某个 API 不确定
CloudBase Auth v2 将用户登录的位置与后端代码运行的位置分离开来:
在实践中,Node 代码通常执行以下一项或多项操作:
auth.getUserInfo() 读取 uid、openId 和 customUserId。uid 时,使用 auth.getEndUserInfo(uid)。auth.queryUserInfo({ platform, platformId, uid? })。auth.createTicket(customUserId, options) 并将票据返回给受信任的客户端。auth.getClientIP() 返回调用者 IP,你可以将其用于审计日志、异常检测或访问控制。本文档后面的场景将这些职责转化为明确、可复制粘贴的模式。
此技能涵盖 CloudBase Node SDK 上的以下 auth 方法。在使用此技能时,将这些方法签名视为 Node 身份验证流程唯一受支持的入口点:
getUserInfo(): IGetUserInfoResult 返回当前调用者的 { openId, appId, uid, customUserId }。getEndUserInfo(uid?: string, opts?: ICustomReqOpts): Promise<{ userInfo: EndUserInfo; requestId?: string }> 返回给定 uid 或当前调用者(当省略 uid 时)的详细 CloudBase 终端用户资料。queryUserInfo(query: IUserInfoQuery, opts?: ICustomReqOpts): Promise<{ userInfo: EndUserInfo; requestId?: string }> 通过登录标识符(platform + platformId)或 uid 查找用户。getClientIP(): string 在受支持的环境(例如云函数)中运行时,返回调用者的 IP 地址。createTicket(customUserId: string, options?: ICreateTicketOpts): string 为给定的 customUserId 创建一个自定义登录票据,客户端可以将其交换为 CloudBase 登录。EndUserInfo、IUserInfoQuery 和 ICreateTicketOpts 的确切字段名和允许值由官方 CloudBase Node SDK 类型定义和文档定义。编写 Node 代码时,请勿猜测结构;遵循 SDK 类型和本文档中的示例。
当编写需要与 Auth 交互的 CloudBase 云函数时使用:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
exports.main = async (event, context) => {
// 你的逻辑写在这里
};
关键点:
env。当你需要知道谁在调用你的云函数时使用:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
exports.main = async (event, context) => {
const { openId, appId, uid, customUserId } = auth.getUserInfo();
console.log("Caller identity", { openId, appId, uid, customUserId });
// 使用 uid / customUserId 进行授权决策
// 例如,检查角色、权限或数据所有权
};
最佳实践:
uid 视为规范的 CloudBase 用户标识符。customUserId。openId/appId 进行授权;它们是微信特定的标识符。当你知道用户的 CloudBase uid(例如,来自数据库记录)并且需要详细的资料信息时使用:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
exports.main = async (event, context) => {
const uid = "user-uid";
try {
const { userInfo } = await auth.getEndUserInfo(uid);
console.log("User profile", userInfo);
} catch (error) {
console.error("Failed to get end user info", error.message);
}
};
最佳实践:
getEndUserInfo;不要直接将其暴露给不受信任的客户端。当你想要当前调用者的完整资料,而无需手动传递 uid 时使用:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
exports.main = async (event, context) => {
try {
const { userInfo } = await auth.getEndUserInfo();
console.log("Current caller profile", userInfo);
} catch (error) {
console.error("Failed to get current caller profile", error.message);
}
};
这依赖于环境提供调用者的身份(例如,在 CloudBase 云函数内)。如果在没有调用者上下文的地方调用,请参考官方文档并优雅地处理错误。
当你只知道用户的登录标识符(电话、邮箱、用户名或自定义 ID)并需要其 CloudBase 资料时使用:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
exports.main = async (event, context) => {
try {
// 通过电话号码查找
const { userInfo: byPhone } = await auth.queryUserInfo({
platform: "PHONE",
platformId: "+86 13800000000",
});
// 通过邮箱查找
const { userInfo: byEmail } = await auth.queryUserInfo({
platform: "EMAIL",
platformId: "test@example.com",
});
// 通过 customUserId 查找
const { userInfo: byCustomId } = await auth.queryUserInfo({
platform: "CUSTOM",
platformId: "your-customUserId",
});
console.log({ byPhone, byEmail, byCustomId });
} catch (error) {
console.error("Failed to query user info", error.message);
}
};
最佳实践:
uid 时,优先使用它;仅在需要时使用 queryUserInfo。platformId 使用你注册时使用的确切格式(例如,+86 + 电话号码)。用于日志记录或基本的基于 IP 的检查:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
exports.main = async (event, context) => {
const ip = auth.getClientIP();
console.log("Caller IP", ip);
// 例如,阻止或标记可疑 IP
};
自定义登录允许你保留现有的用户系统,同时将每个用户映射到 CloudBase 账户。
在签发票据之前,从 CloudBase 控制台安装自定义登录私钥文件并在 Node 中加载:
import tcb from "@cloudbase/node-sdk";
import path from "node:path";
const app = tcb.init({
env: "your-env-id",
credentials: require(path.join(__dirname, "tcb_custom_login.json")),
});
const auth = app.auth();
保持 tcb_custom_login.json 的机密性,切勿将其打包到前端代码中。
在已经认证了你自己的用户并希望让他们登录 CloudBase 的后端代码中使用:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({
env: "your-env-id",
credentials: require("/secure/path/to/tcb_custom_login.json"),
});
const auth = app.auth();
exports.main = async (event, context) => {
const customUserId = "your-customUserId";
const ticket = auth.createTicket(customUserId, {
refresh: 3600 * 1000, // access_token 刷新间隔(毫秒)
expire: 24 * 3600 * 1000, // 票据过期时间(毫秒)
});
// 将票据返回给受信任的客户端(例如,通过 HTTP 响应)
return { ticket };
};
customUserId 的限制(来自官方文档):
_-#@(){}[]:.,<>+#~。最佳实践:
customUserId 存储在你自己的用户数据库中,并保持其长期稳定。customUserId 重复用于多个不同的个人。此技能仅涵盖 Node 端 的票据签发。对于 客户端 流程:
@cloudbase/js-sdk 的自定义登录支持:
ticket 的后端端点。auth.setCustomSignFunc(async () => ticketFromBackend)。auth.signInWithCustomTicket() 完成登录。保持职责清晰:
uid 视为主键。customUserId 用作与你自己的用户系统的桥梁。uid、角色和所有权执行授权检查,而不仅仅是登录成功。getEndUserInfo / queryUserInfo 结果直接暴露给客户端。auth.* 调用返回 Promise 时,将其包装在 try/catch 中。error.message(以及 error.code,如果存在),但避免记录敏感数据。tcb_custom_login.json。当你需要执行以下操作时,请使用此 Node Auth 技能:
uid 或登录标识符查找 CloudBase 用户。对于端到端体验,请将此技能与以下内容配对使用:
@cloudbase/js-sdk 的浏览器端登录和用户体验)。将官方 CloudBase Auth Node SDK 文档视为 Node 身份验证 API 的规范参考,并将本文档中的场景视为经过验证的最佳实践构建块。
每周安装次数
546
代码仓库
GitHub 星标数
39
首次出现
Jan 22, 2026
安全审计
安装于
codex479
opencode478
gemini-cli468
github-copilot455
cursor450
kimi-cli446
Use this skill whenever the task involves server-side authentication or identity in a CloudBase project, and the code is running in Node.js , for example:
Do NOT use this skill for:
@cloudbase/js-sdk (handle those with the auth-web skill, not this Node skill).When the user request mixes frontend and backend concerns (e.g. "build a web login page and a Node API that knows the user"), treat them separately:
When you load this skill to work on a task:
Ask the user:
* Where does this Node code run?
* CloudBase 云函数
* Long‑running Node service using CloudBase
* What do they need from auth?
* Just the **caller identity** for authorization?
* **Look up arbitrary users** by UID / login identifier?
* **Bridge their own user system** into CloudBase via custom login?
2. Confirm CloudBase environment and SDK
* Ask for:
* `env` – CloudBase environment ID
* Install the latest `@cloudbase/node-sdk` from npm if it is not already available.
* Always initialize the SDK using this pattern (values can change, shape must not):
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
3. Pick the relevant scenario from this file
* For **caller identity inside a function** , use the `getUserInfo` scenarios.
* For **full user profile or admin lookup** , use the `getEndUserInfo` and `queryUserInfo` scenarios.
* For **client systems that already have their own users** , use the **custom login ticket** scenarios built on `createTicket`.
* For **logging / security** , use the `getClientIP` scenario.
4. Follow Node SDK API shapes exactly
* Treat all `auth.*` methods and parameter shapes in this file as canonical.
* You may change variable names and framework (e.g. Express vs 云函数 handler), but **do not change SDK method names or parameter fields**.
* If you see a method in older code that is not listed here or in the Node SDK docs mirror, treat it as suspect and avoid using it.
5. If you are unsure about an API
* Consult the official CloudBase Auth Node SDK documentation.
* Only use methods and shapes that appear in the official documentation.
* If you cannot find an API you want:
* Prefer composing flows from the documented methods, or
* Explain that this skill only covers Node SDK auth, and suggest using the relevant CloudBase Web or HTTP auth documentation for client-side or raw-HTTP flows.
CloudBase Auth v2 separates where users log in from where backend code runs :
In practice, Node code usually does one or more of:
Identify the current caller
auth.getUserInfo() to read uid, openId, and customUserId.Look up other users
auth.getEndUserInfo(uid) when you know the CloudBase uid.auth.queryUserInfo({ platform, platformId, uid? }) when you only have login identifiers such as phone, email, username, or a custom ID.Issue custom login tickets
The scenarios later in this file turn these responsibilities into explicit, copy‑pasteable patterns.
This skill covers the following auth methods on the CloudBase Node SDK. Treat these method signatures as the only supported entry points for Node auth flows when using this skill:
getUserInfo(): IGetUserInfoResult Returns { openId, appId, uid, customUserId } for the current caller.
getEndUserInfo(uid?: string, opts?: ICustomReqOpts): Promise<{ userInfo: EndUserInfo; requestId?: string }> Returns detailed CloudBase end‑user profile for a given uid or for the current caller (when uid is omitted).
queryUserInfo(query: IUserInfoQuery, opts?: ICustomReqOpts): Promise<{ userInfo: EndUserInfo; requestId?: string }> Finds a user by login identifier (platform + platformId) or .
The exact field names and allowed values for EndUserInfo, IUserInfoQuery, and ICreateTicketOpts are defined by the official CloudBase Node SDK typings and documentation. When writing Node code, do not guess shapes; follow the SDK types and the examples in this file.
Use this when writing a CloudBase 云函数 that needs to interact with Auth:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
exports.main = async (event, context) => {
// Your logic here
};
Key points:
env as configured for the function’s CloudBase 环境.Use this when you need to know who is calling your cloud function:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
exports.main = async (event, context) => {
const { openId, appId, uid, customUserId } = auth.getUserInfo();
console.log("Caller identity", { openId, appId, uid, customUserId });
// Use uid / customUserId for authorization decisions
// e.g. check roles, permissions, or data ownership
};
Best practices:
uid as the canonical CloudBase user identifier.customUserId only when you have enabled 自定义登录 and mapped your own users.openId/appId alone for authorization; they are WeChat‑specific identifiers.Use this when you know a user’s CloudBase uid (for example, from a database record) and you need detailed profile information:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
exports.main = async (event, context) => {
const uid = "user-uid";
try {
const { userInfo } = await auth.getEndUserInfo(uid);
console.log("User profile", userInfo);
} catch (error) {
console.error("Failed to get end user info", error.message);
}
};
Best practices:
getEndUserInfo from trusted backend code only; do not expose it directly to untrusted clients.Use this when you want the current caller’s full profile without manually passing uid:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
exports.main = async (event, context) => {
try {
const { userInfo } = await auth.getEndUserInfo();
console.log("Current caller profile", userInfo);
} catch (error) {
console.error("Failed to get current caller profile", error.message);
}
};
This relies on the environment providing the caller’s identity (e.g. within a CloudBase 云函数). If called where no caller context exists, refer to the official docs and handle errors gracefully.
Use this when you only know a user’s login identifier (phone, email, username, or custom ID) and need their CloudBase profile:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
exports.main = async (event, context) => {
try {
// Find by phone number
const { userInfo: byPhone } = await auth.queryUserInfo({
platform: "PHONE",
platformId: "+86 13800000000",
});
// Find by email
const { userInfo: byEmail } = await auth.queryUserInfo({
platform: "EMAIL",
platformId: "test@example.com",
});
// Find by customUserId
const { userInfo: byCustomId } = await auth.queryUserInfo({
platform: "CUSTOM",
platformId: "your-customUserId",
});
console.log({ byPhone, byEmail, byCustomId });
} catch (error) {
console.error("Failed to query user info", error.message);
}
};
Best practices:
uid when you already have it; use queryUserInfo only when needed.platformId uses the exact format you used at sign‑up (e.g. +86 + phone number).Use this for logging or basic IP‑based checks:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
exports.main = async (event, context) => {
const ip = auth.getClientIP();
console.log("Caller IP", ip);
// e.g. block or flag suspicious IPs
};
Custom login lets you keep your existing user system while still mapping each user to a CloudBase account.
Before issuing tickets, install the custom login private key file from the CloudBase console and load it in Node:
import tcb from "@cloudbase/node-sdk";
import path from "node:path";
const app = tcb.init({
env: "your-env-id",
credentials: require(path.join(__dirname, "tcb_custom_login.json")),
});
const auth = app.auth();
Keep tcb_custom_login.json secret and never bundle it into frontend code.
Use this in backend code that has already authenticated your own user and wants to let them log into CloudBase:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({
env: "your-env-id",
credentials: require("/secure/path/to/tcb_custom_login.json"),
});
const auth = app.auth();
exports.main = async (event, context) => {
const customUserId = "your-customUserId";
const ticket = auth.createTicket(customUserId, {
refresh: 3600 * 1000, // access_token refresh interval (ms)
expire: 24 * 3600 * 1000, // ticket expiration time (ms)
});
// Return the ticket to the trusted client (e.g. via HTTP response)
return { ticket };
};
Constraints for customUserId (from official docs):
_-#@(){}[]:.,<>+#~.Best practices:
customUserId in your own user database and keep it stable over time.customUserId for multiple distinct people.This skill only covers Node-side ticket issuance. For the client-side flow:
@cloudbase/js-sdk's custom login support:
ticket.auth.setCustomSignFunc(async () => ticketFromBackend).auth.signInWithCustomTicket() to finish login.Keep the responsibility clear:
Single source of truth for identity
uid as the primary key when relating end‑user records.customUserId only as a bridge to your own user system.Least privilege
uid, roles, and ownership, not just login success.getEndUserInfo / queryUserInfo results directly to clients.Error handling
auth.* calls in try/catch when they return promises.Use this Node Auth skill whenever you need to:
uid or login identifier.For end‑to‑end experiences, pair this skill with:
@cloudbase/js-sdk).Treat the official CloudBase Auth Node SDK documentation as the canonical reference for Node auth APIs, and treat the scenarios in this file as vetted best‑practice building blocks.
Weekly Installs
546
Repository
GitHub Stars
39
First Seen
Jan 22, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex479
opencode478
gemini-cli468
github-copilot455
cursor450
kimi-cli446
Supabase Postgres 最佳实践指南 - 8大类别性能优化规则与SQL示例
57,300 周安装
auth.createTicket(customUserId, options) and return the ticket to a trusted client.Log client IP for security
auth.getClientIP() returns the caller IP, which you can use for audit logs, anomaly detection, or access control.uidgetClientIP(): string Returns the caller’s IP address when running in a supported environment (e.g. 云函数).
createTicket(customUserId: string, options?: ICreateTicketOpts): string Creates a custom login ticket for the given customUserId that clients can exchange for a CloudBase login.
error.message (and error.code if present), but avoid logging sensitive data.Security
tcb_custom_login.json as you would any private key.