Loading...
Loading...
Know a signed-in user's name, email or organization in a canister, not only their principal. Internet Identity signs an attribute bundle alongside the delegation, and the backend verifies the signer, the frontend origin and a nonce it issued itself before believing any of it. Use when a canister must know something about the caller beyond their principal: filling a profile, showing a name the user never typed into your app, contacting them, or gating access or an allowlist on an address the user provably controls; and when the backend rejects a bundle the frontend has just obtained. Covers the frontend request, scoping attributes to the account signed in with, and the identity-attributes library for Motoko and Rust. Assumes sign-in already works: load user-sign-in first. Do NOT use for the sign-in flow itself, for an email address the user typed in (that is ordinary app input, which II has not checked), or for an agent or CLI acting as a user (agent-web-identity).
npx skill4agent add dfinity/icskills user-attributes@icp-sdk/authuser-sign-infrontend_originsmo:identity-attributesmo:coremocincludeidentity-attributesic-cdk_internet_identity_sign_in_start_internet_identity_sign_in_finishidentity-attributesrequestAttributes({ 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 |
emailverified_emailemailscopedKeys| Call | Keys | Default |
|---|---|---|
| | |
| | same |
| | same |
| | |
keysscopedKeys({ openIdProvider: 'google', keys: ['name', 'verified_email'] })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;
}openIdProviderssoDomainscopedKeys@icp-sdk/auth/clientscopedKeys({ openIdProvider: "google", keys: ["name", "verified_email"] })scopedKeys({ ssoDomain: "acme.com" })implicit:nonceimplicit:originimplicit:issued_at_timestamp_nscanisters:
- 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_signersfrontend_originsFrontendOriginsNotConfigured{ name, email, sso }emailverified_emailopenid:<provider>:verified_emailverified_emailemailnameemailsso:<domain>:namesso:<domain>:emailtrusted_sso_domainsssossovariant { 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_start[dependencies]
identity-attributes = "0.4.1"
core = "2.5.0"
[toolchain]
moc = "1.6.0"include IdentityAttributes({ onVerified })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)
};
};[dependencies]
candid = "0.10"
ic-cdk = "0.20.1"
identity-attributes = "0.1"#[identity_attributes]asyncuse 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)requestAttributes_internet_identity_sign_in_startimplicit:noncerdmx6-jaaaa-aaaaa-aaadq-caiidentity-attributestrusted_attribute_signersfrontend_originsmsg_caller_info_signer()msg_caller_info_data()email = "admin@you.com"{tid}microsofthttps://login.microsoftonline.com/{tid}/v2.0openid:https://login.microsoftonline.com/{tid}/v2.0:emailemailemailverified_emailverified_emailverified_emailsso:sso:<domain>:emailtrusted_sso_domainsorganization-sign-in