user-attributes

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

User Attributes

用户属性

Prerequisites

前置条件

This skill assumes a working Internet Identity sign-in built with
@icp-sdk/auth
: load the
user-sign-in
skill first. The attribute bundle travels alongside a delegation, so there is nothing here to request without one.
The
frontend_origins
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.
  • For a Motoko backend:
    mo:identity-attributes
    >= 0.4.0 (mops). It pulls in
    mo:core
    >= 2.5.0 and requires
    moc
    >= 1.6.0 for
    include
    .
  • For a Rust backend: the
    identity-attributes
    crate and
    ic-cdk
    >= 0.20.1.
此 skill 假定已有一个使用
@icp-sdk/auth
构建且可正常工作的 Internet Identity 登录流程:请先加载
user-sign-in
skill。属性 bundle 会随 delegation 一同传输,因此在没有 delegation 的情况下,这里没有任何内容可供请求。
下面配置的
frontend_origins
值必须是用于派生身份属性的 origin;如果应用固定了某个 origin,则必须是该应用的 主 origin,而不是用户当前恰好访问的 origin。dfx suite 的默认配置通常会在此处出错。
  • 对于 Motoko 后端:
    mo:identity-attributes
    >= 0.4.0 (mops)。它会引入
    mo:core
    >= 2.5.0,并要求
    moc
    >= 1.6.0 以支持
    include
    。
  • 对于 Rust 后端:
    identity-attributes
    crate 和
    ic-cdk
    >= 0.20.1。

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:
_internet_identity_sign_in_start
issues a nonce,
_internet_identity_sign_in_finish
verifies the bundle. The
identity-attributes
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.
当后端需要 principal 之外的信息时,II 会在 delegation 之外返回已签名的属性 bundle。后端暴露两个方法:
_internet_identity_sign_in_start
签发 nonce,
_internet_identity_sign_in_finish
验证 bundle。
identity-attributes
库在 Motoko 和 Rust 中都添加了这两个方法,并采用相同的检查、相同的环境变量和相同的 Candid 类型,因此无需改动前端即可对接任一种后端。

Keys

键

requestAttributes({ keys, nonce })
requires both; there is no default key set.
KeyMeaningUse for
name
Display name from the user's II-linked accountPersonalisation
email
Raw address from the II-linked account; II does not check itContact info, mailing lists
verified_email
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
email
and
verified_email
for fallback: when verified, both carry the same value; otherwise only
email
arrives.
scopedKeys
scopes keys to the account the user signs in with, so they are shared in the same step with no extra prompt:
CallKeysDefault
keys
scopedKeys({ openIdProvider: 'google' })
openid:https://accounts.google.com:<key>
name
,
email
,
verified_email
scopedKeys({ openIdProvider: 'apple' })
openid:https://appleid.apple.com:<key>
same
scopedKeys({ openIdProvider: 'microsoft' })
openid:https://login.microsoftonline.com/{tid}/v2.0:<key>
(
{tid}
literal)
same
scopedKeys({ ssoDomain: 'acme.com' })
sso:acme.com:<key>
name
,
email
(no
verified_email
)
Pass
keys
to narrow, e.g.
scopedKeys({ openIdProvider: 'google', keys: ['name', 'verified_email'] })
.
requestAttributes({ keys, nonce })
的两个参数均为必填;不存在默认键集。
键含义用途
name
用户 II 关联账户中的显示名称个性化
email
II 关联账户中的原始地址;II 不会检查它联系信息、邮件列表
verified_email
仅当 II 确认用户控制该地址时才存在(OpenID 提供商将其标记为已验证,或用户通过 II 验证)访问控制;唯一可用于授权的邮箱
请同时请求
email
和
verified_email
以实现回退:验证通过时两者值相同;否则只会收到
email
。
scopedKeys
将键限定到用户登录所用的账户,因此可在同一步骤中获取,且不会产生额外提示:
调用键默认
keys
scopedKeys({ openIdProvider: 'google' })
openid:https://accounts.google.com:<key>
name
,
email
,
verified_email
scopedKeys({ openIdProvider: 'apple' })
openid:https://appleid.apple.com:<key>
相同
scopedKeys({ openIdProvider: 'microsoft' })
openid:https://login.microsoftonline.com/{tid}/v2.0:<key>
(
{tid}
为字面量)
相同
scopedKeys({ ssoDomain: 'acme.com' })
sso:acme.com:<key>
name
,
email
(无
verified_email
)
传入
keys
可进一步缩小范围,例如
scopedKeys({ 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
openIdProvider
or
ssoDomain
, add
scopedKeys
to the
@icp-sdk/auth/client
import, and request
scopedKeys({ openIdProvider: "google", keys: ["name", "verified_email"] })
or
scopedKeys({ ssoDomain: "acme.com" })
instead; the rest is unchanged.
Every bundle carries three implicit fields the backend MUST verify:
implicit:nonce
(one it issued and has not consumed),
implicit:origin
(a trusted frontend origin),
implicit:issued_at_timestamp_ns
(fresh, typically within five minutes).
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;
}
对于一键登录,请使用
openIdProvider
或
ssoDomain
构建客户端,从
@icp-sdk/auth/client
导入时加入
scopedKeys
,并改为请求
scopedKeys({ openIdProvider: "google", keys: ["name", "verified_email"] })
或
scopedKeys({ ssoDomain: "acme.com" })
;其余部分保持不变。
每个 bundle 都包含三个隐式字段,后端必须(MUST)对其进行验证:
implicit:nonce
(由后端签发且尚未使用)、
implicit:origin
(可信的前端 origin),以及
implicit:issued_at_timestamp_ns
(必须新鲜,通常在五分钟以内)。

Backend

后端

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
trusted_attribute_signers
is unset or does not list the bundle's signer. Unset
frontend_origins
makes the finish method return
FrontendOriginsNotConfigured
.
两种语言使用相同的环境变量:
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"
当
trusted_attribute_signers
未设置,或其中未列出 bundle 的签名者时,携带 bundle 的调用会被拒绝。未设置
frontend_origins
时,finish 方法会返回
FrontendOriginsNotConfigured
。

What the callback receives

回调接收到什么

Your callback runs only for a bundle that passes every check below, and receives the caller with
{ name, email, sso }
(each optional):
  • OpenID and unscoped sources:
    email
    comes from
    verified_email
    (or
    openid:<provider>:verified_email
    ), which is why the frontend requests
    verified_email
    . The unverified
    email
    key is never read.
  • SSO sources:
    name
    and
    email
    come from
    sso:<domain>:name
    /
    sso:<domain>:email
    , accepted only for a domain in
    trusted_sso_domains
    , and
    sso
    is that domain. Otherwise
    sso
    is empty.
只有 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
variant { ok; err : Error }
, so the frontend checks
"err" in result
. It checks, in order:
CheckError
A bundle is attached
NoAttributes
It decodes to an ICRC-3
Value::Map
MalformedCandid
frontend_origins
is set
FrontendOriginsNotConfigured
implicit:origin
is one of
frontend_origins
FrontendOriginMismatch { expected, got }
implicit:issued_at_timestamp_ns
is at most five minutes old
Stale { ageNs }
implicit:nonce
was issued here and not consumed
UnknownNonce
A required implicit field is present
MissingField
Every
sso:<domain>:*
key's domain is trusted
UntrustedSsoSource { domain }
Name and email come from
sso:
keys or from others, never both
MixedSsoSources { ssoKeys, otherKeys }
Each field comes from one key, and
sso:
keys from one domain
AmbiguousAttribute { field, sources }
UnknownNonce
answers a nonce older than five minutes, one already spent, and, in Rust, one issued before an upgrade. Treat it as "retry from
_internet_identity_sign_in_start
with a fresh nonce", not as a bug.
finish 方法返回 Candid
variant { ok; err : Error }
,因此前端会检查
"err" in result
。它按以下顺序进行检查:
检查项错误
已附加 bundle
NoAttributes
可解码为 ICRC-3
Value::Map
MalformedCandid
已设置
frontend_origins
FrontendOriginsNotConfigured
implicit:origin
是
frontend_origins
之一
FrontendOriginMismatch { expected, got }
implicit:issued_at_timestamp_ns
的时间不超过五分钟
Stale { ageNs }
implicit:nonce
是此处签发且尚未使用的 nonce
UnknownNonce
存在所有必需的隐式字段
MissingField
每个
sso:<domain>:*
键的域名均受信任
UntrustedSsoSource { domain }
姓名和邮箱均来自
sso:
键或均来自其他键,两者不可混用
MixedSsoSources { ssoKeys, otherKeys }
每个字段仅来自一个键,且
sso:
键仅来自一个域
AmbiguousAttribute { field, sources }
UnknownNonce
表示 nonce 的有效期超过五分钟、已被使用,或者在 Rust 中是在升级前签发的。应将其视为从
_internet_identity_sign_in_start
发起重试并使用新的 nonce,而不要视为 bug。

Motoko

Motoko

toml
[dependencies]
identity-attributes = "0.4.1"
core                = "2.5.0"

[toolchain]
moc = "1.6.0"
include IdentityAttributes({ onVerified })
injects both methods:
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]
marks the callback and adds both methods. The function cannot be
async
or generic:
rust
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()
and
identity_attributes::sign_in_finish(on_verified)
are the functions behind the two methods, for a canister that defines them itself.
toml
[dependencies]
candid = "0.10"
ic-cdk = "0.20.1"
identity-attributes = "0.1"
#[identity_attributes]
会标记回调并添加这两个方法。该函数不能是
async
,也不能是泛型:
rust
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)
是这两个方法背后的函数,适用于自行定义这些方法的 canister。

Mistakes That Break Your Build

导致构建失败的错误

  1. Generating the attribute nonce on the frontend. The nonce passed to
    requestAttributes
    MUST come from the backend (
    _internet_identity_sign_in_start
    ), or the canister cannot check that the bundle's
    implicit:nonce
    is one it issued, and replay protection is gone.
  2. 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
    rdmx6-jaaaa-aaaaa-aaadq-cai
    . Use the
    identity-attributes
    library with
    trusted_attribute_signers
    and
    frontend_origins
    configured. Hand-written Rust must check
    msg_caller_info_signer()
    before reading
    msg_caller_info_data()
    , or an attacker canister can forge
    email = "admin@you.com"
    .
  3. Substituting
    {tid}
    in the Microsoft scoped-key prefix.
    The
    microsoft
    provider URL is the literal
    https://login.microsoftonline.com/{tid}/v2.0
    ; keys look like
    openid:https://login.microsoftonline.com/{tid}/v2.0:email
    exactly. Filling in a tenant ID misses every lookup.
  4. Treating
    email
    as verified.
    email
    is the raw address from the user's II-linked account; II does not check it, so treat it as user input.
    verified_email
    is 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 on
    verified_email
    only. There is no
    verified_email
    under
    sso:
    : the organization's own provider asserts
    sso:<domain>:email
    , so trust it only for domains in
    trusted_sso_domains
    . What an organization can and cannot assert about its own staff is the
    organization-sign-in
    skill.
  1. 在前端生成属性 nonce。 传给
    requestAttributes
    的 nonce 必须来自后端(
    _internet_identity_sign_in_start
    ),否则 canister 无法检查 bundle 的
    implicit:nonce
    是否由其签发,重放保护也将失效。
  2. 读取属性数据时未验证签名者。 IC 会验证签名,但不会验证是谁进行了签名:任何 canister 都可以生成有效 bundle。可信签名者为
    rdmx6-jaaaa-aaaaa-aaadq-cai
    。请在配置了
    trusted_attribute_signers
    和
    frontend_origins
    的情况下使用
    identity-attributes
    库。手写 Rust 必须在读取
    msg_caller_info_data()
    之前检查
    msg_caller_info_signer()
    ,否则攻击者控制的 canister 可以伪造
    email = "admin@you.com"
    。
  3. 替换 Microsoft scoped-key 前缀中的
    {tid}
    。
    microsoft
    提供商 URL 是字面量
    https://login.microsoftonline.com/{tid}/v2.0
    ;键的形式正是
    openid:https://login.microsoftonline.com/{tid}/v2.0:email
    。填入 tenant ID 会导致所有查找失败。
  4. 将
    email
    视为已验证。
    email
    是用户 II 关联账户中的原始地址;II 不会检查它,因此应将其视为用户输入。
    verified_email
    仅在 II 确认用户控制该地址时存在:OpenID 提供商将其标记为已验证,或用户通过 II 验证。只能基于
    verified_email
    控制访问权限。
    sso:
    下不存在
    verified_email
    :组织自己的身份提供商会断言
    sso:<domain>:email
    ,因此仅应信任
    trusted_sso_domains
    中域名的对应值。组织对于其员工能够或不能作出哪些声明,请参阅
    organization-sign-in
    skill。