user-attributes
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseUser Attributes
用户属性
Prerequisites
前置条件
This skill assumes a working Internet Identity sign-in built with : load the skill first. The attribute bundle travels alongside a delegation, so there is nothing here to request without one.
@icp-sdk/authuser-sign-inThe value configured below must be the origin identities are derived for, the primary origin where the app has pinned one, not the origin the user happens to be visiting. A suite gets this wrong by default.
frontend_origins- For a Motoko backend: >= 0.4.0 (mops). It pulls in
mo:identity-attributes>= 2.5.0 and requiresmo:core>= 1.6.0 formoc.include - For a Rust backend: the crate and
identity-attributes>= 0.20.1.ic-cdk
此 skill 假定已有一个使用 构建且可正常工作的 Internet Identity 登录流程:请先加载 skill。属性 bundle 会随 delegation 一同传输,因此在没有 delegation 的情况下,这里没有任何内容可供请求。
@icp-sdk/authuser-sign-in下面配置的 值必须是用于派生身份属性的 origin;如果应用固定了某个 origin,则必须是该应用的 主 origin,而不是用户当前恰好访问的 origin。dfx suite 的默认配置通常会在此处出错。
frontend_origins- 对于 Motoko 后端:>= 0.4.0 (mops)。它会引入
mo:identity-attributes>= 2.5.0,并要求mo:core>= 1.6.0 以支持moc。include - 对于 Rust 后端:crate 和
identity-attributes>= 0.20.1。ic-cdk
How it works
工作原理
When the backend needs more than the principal, II returns a signed attribute bundle alongside the delegation. The backend exposes two methods: issues a nonce, verifies the bundle. The library adds both, in Motoko and in Rust, with the same checks, the same environment variables and the same Candid types, so one frontend works against either backend.
_internet_identity_sign_in_start_internet_identity_sign_in_finishidentity-attributes当后端需要 principal 之外的信息时,II 会在 delegation 之外返回已签名的属性 bundle。后端暴露两个方法: 签发 nonce, 验证 bundle。 库在 Motoko 和 Rust 中都添加了这两个方法,并采用相同的检查、相同的环境变量和相同的 Candid 类型,因此无需改动前端即可对接任一种后端。
_internet_identity_sign_in_start_internet_identity_sign_in_finishidentity-attributesKeys
键
requestAttributes({ keys, nonce })| Key | Meaning | Use for |
|---|---|---|
| Display name from the user's II-linked account | Personalisation |
| Raw address from the II-linked account; II does not check it | Contact info, mailing lists |
| Present only when II established the user controls the address (an OpenID provider marked it verified, or the user verified it with II) | Access gating; the only email to authorise on |
Request both and for fallback: when verified, both carry the same value; otherwise only arrives.
emailverified_emailemailscopedKeys| Call | Keys | Default |
|---|---|---|
| | |
| | same |
| | same |
| | |
Pass to narrow, e.g. .
keysscopedKeys({ openIdProvider: 'google', keys: ['name', 'verified_email'] })requestAttributes({ keys, nonce })| 键 | 含义 | 用途 |
|---|---|---|
| 用户 II 关联账户中的显示名称 | 个性化 |
| II 关联账户中的原始地址;II 不会检查它 | 联系信息、邮件列表 |
| 仅当 II 确认用户控制该地址时才存在(OpenID 提供商将其标记为已验证,或用户通过 II 验证) | 访问控制;唯一可用于授权的邮箱 |
请同时请求 和 以实现回退:验证通过时两者值相同;否则只会收到 。
emailverified_emailemailscopedKeys| 调用 | 键 | 默认 |
|---|---|---|
| | |
| | 相同 |
| | 相同 |
| | |
传入 可进一步缩小范围,例如 。
keysscopedKeys({ openIdProvider: 'google', keys: ['name', 'verified_email'] })Frontend
前端
javascript
import { AuthClient } from "@icp-sdk/auth/client";
import { AttributesIdentity } from "@icp-sdk/core/identity";
import { HttpAgent, Actor } from "@icp-sdk/core/agent";
import { safeGetCanisterEnv } from "@icp-sdk/core/agent/canister-env";
import { Principal } from "@icp-sdk/core/principal";
const II_PRINCIPAL = "rdmx6-jaaaa-aaaaa-aaadq-cai";
const rootKey = safeGetCanisterEnv()?.IC_ROOT_KEY;
async function signInWithAttributes(authClient, canisterId, idl) {
// Anonymous handle, used only to ask for the nonce.
const anonymousActor = Actor.createActor(idl, { agent: await HttpAgent.create({ rootKey }), canisterId });
// In parallel, one interaction for the user. `nonce` is a function the client
// calls when it needs the value, so the request is in flight while II opens.
const signInPromise = authClient.signIn();
const attributesPromise = authClient.requestAttributes({
keys: ["name", "verified_email"],
nonce: () => anonymousActor._internet_identity_sign_in_start(),
});
const identity = await signInPromise;
const attributes = await attributesPromise;
// The bundle travels as sender_info on each call made with this identity.
const verifiedAgent = await HttpAgent.create({
identity: new AttributesIdentity({
inner: identity,
attributes,
signer: { canisterId: Principal.fromText(II_PRINCIPAL) },
}),
rootKey,
});
const verifiedActor = Actor.createActor(idl, { agent: verifiedAgent, canisterId });
const result = await verifiedActor._internet_identity_sign_in_finish();
if ("err" in result) {
throw new Error(`Attribute verification failed: ${JSON.stringify(result.err)}`);
}
return identity;
}For one-click sign-in, build the client with or , add to the import, and request or instead; the rest is unchanged.
openIdProviderssoDomainscopedKeys@icp-sdk/auth/clientscopedKeys({ openIdProvider: "google", keys: ["name", "verified_email"] })scopedKeys({ ssoDomain: "acme.com" })Every bundle carries three implicit fields the backend MUST verify: (one it issued and has not consumed), (a trusted frontend origin), (fresh, typically within five minutes).
implicit:nonceimplicit:originimplicit:issued_at_timestamp_nsjavascript
import { AuthClient } from "@icp-sdk/auth/client";
import { AttributesIdentity } from "@icp-sdk/core/identity";
import { HttpAgent, Actor } from "@icp-sdk/core/agent";
import { safeGetCanisterEnv } from "@icp-sdk/core/agent/canister-env";
import { Principal } from "@icp-sdk/core/principal";
const II_PRINCIPAL = "rdmx6-jaaaa-aaaaa-aaadq-cai";
const rootKey = safeGetCanisterEnv()?.IC_ROOT_KEY;
async function signInWithAttributes(authClient, canisterId, idl) {
// Anonymous handle, used only to ask for the nonce.
const anonymousActor = Actor.createActor(idl, { agent: await HttpAgent.create({ rootKey }), canisterId });
// In parallel, one interaction for the user. `nonce` is a function the client
// calls when it needs the value, so the request is in flight while II opens.
const signInPromise = authClient.signIn();
const attributesPromise = authClient.requestAttributes({
keys: ["name", "verified_email"],
nonce: () => anonymousActor._internet_identity_sign_in_start(),
});
const identity = await signInPromise;
const attributes = await attributesPromise;
// The bundle travels as sender_info on each call made with this identity.
const verifiedAgent = await HttpAgent.create({
identity: new AttributesIdentity({
inner: identity,
attributes,
signer: { canisterId: Principal.fromText(II_PRINCIPAL) },
}),
rootKey,
});
const verifiedActor = Actor.createActor(idl, { agent: verifiedAgent, canisterId });
const result = await verifiedActor._internet_identity_sign_in_finish();
if ("err" in result) {
throw new Error(`Attribute verification failed: ${JSON.stringify(result.err)}`);
}
return identity;
}对于一键登录,请使用 或 构建客户端,从 导入时加入 ,并改为请求 或 ;其余部分保持不变。
openIdProviderssoDomain@icp-sdk/auth/clientscopedKeysscopedKeys({ openIdProvider: "google", keys: ["name", "verified_email"] })scopedKeys({ ssoDomain: "acme.com" })每个 bundle 都包含三个隐式字段,后端必须(MUST)对其进行验证:(由后端签发且尚未使用)、(可信的前端 origin),以及 (必须新鲜,通常在五分钟以内)。
implicit:nonceimplicit:originimplicit:issued_at_timestamp_nsBackend
后端
Configuration
配置
Environment variables, the same for both languages:
yaml
canisters:
- name: backend
settings:
environment_variables:
# Required. A local II (`ii: true`) has the same principal.
trusted_attribute_signers: "rdmx6-jaaaa-aaaaa-aaadq-cai"
# Required, comma-separated. The origin identities are DERIVED for.
frontend_origins: "https://your-app.icp.net"
# Optional, comma-separated; omit to reject all sso:* keys.
trusted_sso_domains: "your-org.com"A call carrying a bundle is rejected when is unset or does not list the bundle's signer. Unset makes the finish method return .
trusted_attribute_signersfrontend_originsFrontendOriginsNotConfigured两种语言使用相同的环境变量:
yaml
canisters:
- name: backend
settings:
environment_variables:
# Required. A local II (`ii: true`) has the same principal.
trusted_attribute_signers: "rdmx6-jaaaa-aaaaa-aaadq-cai"
# Required, comma-separated. The origin identities are DERIVED for.
frontend_origins: "https://your-app.icp.net"
# Optional, comma-separated; omit to reject all sso:* keys.
trusted_sso_domains: "your-org.com"当 未设置,或其中未列出 bundle 的签名者时,携带 bundle 的调用会被拒绝。未设置 时,finish 方法会返回 。
trusted_attribute_signersfrontend_originsFrontendOriginsNotConfiguredWhat the callback receives
回调接收到什么
Your callback runs only for a bundle that passes every check below, and receives the caller with (each optional):
{ name, email, sso }- OpenID and unscoped sources: comes from
email(orverified_email), which is why the frontend requestsopenid:<provider>:verified_email. The unverifiedverified_emailkey is never read.email - SSO sources: and
namecome fromemail/sso:<domain>:name, accepted only for a domain insso:<domain>:email, andtrusted_sso_domainsis that domain. Otherwisessois empty.sso
只有 bundle 通过下列所有检查后,才会调用你的回调;回调会接收到调用者以及 (每个字段均为可选):
{ name, email, sso }- OpenID 和未限定范围的来源:来自
email(或verified_email),这也是前端请求openid:<provider>:verified_email的原因。未经验证的verified_email键绝不会被读取。email - SSO 来源:和
name来自email/sso:<domain>:name,仅当域名位于sso:<domain>:email中时才会接受;trusted_sso_domains即该域名。否则sso为空。sso
Checks and errors
检查项与错误
The finish method returns Candid , so the frontend checks . It checks, in order:
variant { ok; err : Error }"err" in result| Check | Error |
|---|---|
| A bundle is attached | |
It decodes to an ICRC-3 | |
| |
| |
| |
| |
| A required implicit field is present | |
Every | |
Name and email come from | |
Each field comes from one key, and | |
UnknownNonce_internet_identity_sign_in_startfinish 方法返回 Candid ,因此前端会检查 。它按以下顺序进行检查:
variant { ok; err : Error }"err" in result| 检查项 | 错误 |
|---|---|
| 已附加 bundle | |
可解码为 ICRC-3 | |
已设置 | |
| |
| |
| |
| 存在所有必需的隐式字段 | |
每个 | |
姓名和邮箱均来自 | |
每个字段仅来自一个键,且 | |
UnknownNonce_internet_identity_sign_in_startMotoko
Motoko
toml
[dependencies]
identity-attributes = "0.4.1"
core = "2.5.0"
[toolchain]
moc = "1.6.0"include IdentityAttributes({ onVerified })motoko
import IdentityAttributes "mo:identity-attributes";
import Map "mo:core/Map";
import Principal "mo:core/Principal";
persistent actor {
type Profile = { name : ?Text; email : ?Text; sso : ?Text };
let profiles = Map.empty<Principal, Profile>();
include IdentityAttributes({
onVerified = func(caller, attrs) {
profiles.add(caller, attrs);
};
});
public query func getProfile(userId : Principal) : async ?Profile {
profiles.get(userId)
};
};toml
[dependencies]
identity-attributes = "0.4.1"
core = "2.5.0"
[toolchain]
moc = "1.6.0"include IdentityAttributes({ onVerified })motoko
import IdentityAttributes "mo:identity-attributes";
import Map "mo:core/Map";
import Principal "mo:core/Principal";
persistent actor {
type Profile = { name : ?Text; email : ?Text; sso : ?Text };
let profiles = Map.empty<Principal, Profile>();
include IdentityAttributes({
onVerified = func(caller, attrs) {
profiles.add(caller, attrs);
};
});
public query func getProfile(userId : Principal) : async ?Profile {
profiles.get(userId)
};
};Rust
Rust
toml
[dependencies]
candid = "0.10"
ic-cdk = "0.20.1"
identity-attributes = "0.1"#[identity_attributes]asyncrust
use candid::Principal;
use ic_cdk::query;
use identity_attributes::{identity_attributes, IdentityAttributes};
use std::cell::RefCell;
use std::collections::BTreeMap;
thread_local! {
// On the heap to keep the example short: an upgrade clears it.
static PROFILES: RefCell<BTreeMap<Principal, IdentityAttributes>> =
const { RefCell::new(BTreeMap::new()) };
}
#[identity_attributes]
fn on_verified(caller: Principal, attributes: IdentityAttributes) {
PROFILES.with_borrow_mut(|profiles| profiles.insert(caller, attributes));
}
#[query]
fn get_profile(user_id: Principal) -> Option<IdentityAttributes> {
PROFILES.with_borrow(|profiles| profiles.get(&user_id).cloned())
}
ic_cdk::export_candid!();identity_attributes::sign_in_start()identity_attributes::sign_in_finish(on_verified)toml
[dependencies]
candid = "0.10"
ic-cdk = "0.20.1"
identity-attributes = "0.1"#[identity_attributes]asyncrust
use candid::Principal;
use ic_cdk::query;
use identity_attributes::{identity_attributes, IdentityAttributes};
use std::cell::RefCell;
use std::collections::BTreeMap;
thread_local! {
// On the heap to keep the example short: an upgrade clears it.
static PROFILES: RefCell<BTreeMap<Principal, IdentityAttributes>> =
const { RefCell::new(BTreeMap::new()) };
}
#[identity_attributes]
fn on_verified(caller: Principal, attributes: IdentityAttributes) {
PROFILES.with_borrow_mut(|profiles| profiles.insert(caller, attributes));
}
#[query]
fn get_profile(user_id: Principal) -> Option<IdentityAttributes> {
PROFILES.with_borrow(|profiles| profiles.get(&user_id).cloned())
}
ic_cdk::export_candid!();identity_attributes::sign_in_start()identity_attributes::sign_in_finish(on_verified)Mistakes That Break Your Build
导致构建失败的错误
- Generating the attribute nonce on the frontend. The nonce passed to MUST come from the backend (
requestAttributes), or the canister cannot check that the bundle's_internet_identity_sign_in_startis one it issued, and replay protection is gone.implicit:nonce - Reading attribute data without verifying the signer. The IC verifies the signature, not who signed: any canister can produce a valid bundle. The trusted signer is . Use the
rdmx6-jaaaa-aaaaa-aaadq-cailibrary withidentity-attributesandtrusted_attribute_signersconfigured. Hand-written Rust must checkfrontend_originsbefore readingmsg_caller_info_signer(), or an attacker canister can forgemsg_caller_info_data().email = "admin@you.com" - Substituting in the Microsoft scoped-key prefix. The
{tid}provider URL is the literalmicrosoft; keys look likehttps://login.microsoftonline.com/{tid}/v2.0exactly. Filling in a tenant ID misses every lookup.openid:https://login.microsoftonline.com/{tid}/v2.0:email - Treating as verified.
emailis the raw address from the user's II-linked account; II does not check it, so treat it as user input.emailis present only when II established that the user controls the address: an OpenID provider marked it verified, or the user verified it with II. Gate access onverified_emailonly. There is noverified_emailunderverified_email: the organization's own provider assertssso:, so trust it only for domains insso:<domain>:email. What an organization can and cannot assert about its own staff is thetrusted_sso_domainsskill.organization-sign-in
- 在前端生成属性 nonce。 传给 的 nonce 必须来自后端(
requestAttributes),否则 canister 无法检查 bundle 的_internet_identity_sign_in_start是否由其签发,重放保护也将失效。implicit:nonce - 读取属性数据时未验证签名者。 IC 会验证签名,但不会验证是谁进行了签名:任何 canister 都可以生成有效 bundle。可信签名者为 。请在配置了
rdmx6-jaaaa-aaaaa-aaadq-cai和trusted_attribute_signers的情况下使用frontend_origins库。手写 Rust 必须在读取identity-attributes之前检查msg_caller_info_data(),否则攻击者控制的 canister 可以伪造msg_caller_info_signer()。email = "admin@you.com" - 替换 Microsoft scoped-key 前缀中的 。
{tid}提供商 URL 是字面量microsoft;键的形式正是https://login.microsoftonline.com/{tid}/v2.0。填入 tenant ID 会导致所有查找失败。openid:https://login.microsoftonline.com/{tid}/v2.0:email - 将 视为已验证。
email是用户 II 关联账户中的原始地址;II 不会检查它,因此应将其视为用户输入。email仅在 II 确认用户控制该地址时存在:OpenID 提供商将其标记为已验证,或用户通过 II 验证。只能基于verified_email控制访问权限。verified_email下不存在sso::组织自己的身份提供商会断言verified_email,因此仅应信任sso:<domain>:email中域名的对应值。组织对于其员工能够或不能作出哪些声明,请参阅trusted_sso_domainsskill。organization-sign-in