You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Internet Identity (II) is the Internet Computer's native authentication system. Users sign in with passkeys or OpenID accounts (Google, Apple, Microsoft) instead of passwords. Each user receives a unique principal per frontend origin, preventing cross-app tracking.
11
11
12
-
This guide covers setting up II authentication end-to-end: configuring your project, adding login to your frontend, and verifying callers in your backend.
12
+
This guide covers setting up II authentication end-to-end: configuring your project, adding sign-in to your frontend, and verifying callers in your backend.
The `AuthClient` from `@icp-sdk/auth` handles the full login flow: opening the II popup, receiving the delegation, and managing session persistence.
49
+
The `AuthClient` from `@icp-sdk/auth` handles the full sign-in flow: opening the II popup, receiving the delegation, and managing session persistence.
50
50
51
51
### Environment detection
52
52
@@ -77,50 +77,61 @@ function getIdentityProviderUrl() {
77
77
}
78
78
```
79
79
80
-
### Login, logout, and session check
80
+
### Sign in, sign out, and session check
81
81
82
-
Create a single `AuthClient` instance on page load and reuse it for all operations:
82
+
Create a single `AuthClient` instance on page load and reuse it for all operations. The identity provider URL is passed at construction time, not on each sign-in:
console.log("Logged in as:", identity.getPrincipal().toText());
104
-
resolve(identity);
105
-
},
106
-
onError: (error) => {
107
-
console.error("Login failed:", error);
108
-
reject(error);
109
-
},
110
101
});
111
-
});
102
+
console.log("Signed in as:", identity.getPrincipal().toText());
103
+
return identity;
104
+
} catch (error) {
105
+
console.error("Sign-in failed:", error);
106
+
throw error;
107
+
}
112
108
}
113
109
114
-
//Logout
115
-
asyncfunctionlogout() {
116
-
awaitauthClient.logout();
110
+
//Sign out
111
+
asyncfunctionsignOut() {
112
+
awaitauthClient.signOut();
117
113
// Reset UI state or reload
118
114
}
119
115
```
120
116
117
+
`signIn()` returns the new `Identity` directly. It rejects if the user closes the popup or authentication fails, so wrap the call in `try`/`catch` instead of relying on success/error callbacks.
118
+
119
+
### One-click OpenID sign-in
120
+
121
+
To skip the Internet Identity authentication-method screen and send the user straight to a specific OpenID provider, pass `openIdProvider` to the constructor. Supported values are `'google'`, `'apple'`, and `'microsoft'`:
122
+
123
+
```javascript
124
+
constauthClient=newAuthClient({
125
+
identityProvider:getIdentityProviderUrl(),
126
+
openIdProvider:"google",
127
+
});
128
+
```
129
+
130
+
The rest of the flow (`signIn`, `getIdentity`, `signOut`) is unchanged.
131
+
121
132
### Create an authenticated agent
122
133
123
-
After login, create an `HttpAgent` using the delegation identity. The agent signs all subsequent canister calls with the user's delegated key:
134
+
After sign-in, create an `HttpAgent` using the delegation identity. The agent signs all subsequent canister calls with the user's delegated key:
@@ -138,6 +149,84 @@ async function createAuthenticatedActor(identity, canisterId, idlFactory) {
138
149
`safeGetCanisterEnv()` reads the `ic_env` cookie set by the asset canister or Vite dev server (it only works in browser contexts. For Node.js scripts or tests connecting to a **local** replica, create the agent normally and call `awaitagent.fetchRootKey()` explicitly after creation. Never call `fetchRootKey()` against a mainnet endpoint) on mainnet the root key is pre-trusted, and fetching it at runtime exposes a man-in-the-middle risk.
139
150
:::
140
151
152
+
### Requesting identity attributes
153
+
154
+
When a backend canister needs more than just the user's principal (for example, a verified email address), Internet Identity can return signed attributes alongside the delegation. Your backend issues a nonce scoped to a specific action; the frontend requests the attributes during sign-in; the backend verifies the bundle when the user calls the protected method.
155
+
156
+
**Why a backend-issued nonce?** Tying attributes to a canister-issued nonce prevents replay: an intercepted bundle cannot be reused for a different action, on a different user, or after that action expires. The nonce must originate from the canister, not the frontend.
Each signed attribute bundle carries three implicit fields the backend should verify:
201
+
202
+
- `implicit:nonce`: matches the canister-issued nonce, preventing replay across actions and users.
203
+
- `implicit:origin`: the requesting frontend origin, so a malicious dapp cannot forward attributes to a different backend.
204
+
- `implicit:issued_at_timestamp_ns`: issuance time, letting the canister reject stale bundles even when the nonce is still valid.
205
+
206
+
Attributes can also be requested after sign-in, for example to link an email to an existing account. The pattern is the same: the backend issues a nonce for that action, the frontend calls `requestAttributes`, and the backend verifies the result.
207
+
208
+
#### OpenID-scoped attributes
209
+
210
+
When using one-click OpenID sign-in, attributes can be scoped to the provider. The user authenticates and shares attributes in a single step, with no extra prompt:
Your backend canister receives the caller's principal automatically through the IC protocol. You do not pass the principal as a function argument: use `msg.caller` (Motoko) or `ic_cdk::api::msg_caller()` (Rust) to read it.
When the frontend wraps an identity with `AttributesIdentity`, every call carries a verified attribute bundle. Read it on the backend with `msg_caller_info_data` (Rust) or `Prim.callerInfoData` (Motoko). Always verify the signer first: by itself the bundle is signed by *some* canister, and any canister could have signed an arbitrary one. Trust it only when the signer is the Internet Identity backend (`rdmx6-jaaaa-aaaaa-aaadq-cai`).
319
+
320
+
The bundle is Candid-encoded as an [ICRC-3 Value](../../references/internet-identity-spec.md) `Map` with three implicit fields plus the keys you requested:
321
+
322
+
- `implicit:nonce`: must equal a nonce your canister issued for this user and action.
323
+
- `implicit:origin`: must equal a trusted frontend origin.
324
+
- `implicit:issued_at_timestamp_ns`: reject if too old (a few minutes is typical).
325
+
- Plain attribute keys (e.g., `"email"`) for default-scope attributes; OpenID-scoped keys (e.g., `"openid:https://accounts.google.com:email"`) when the frontend used `scopedKeys`.
326
+
327
+
<Tabs syncKey="lang">
328
+
<TabItem label="Motoko">
329
+
330
+
```motoko
331
+
import Prim "mo:prim";
332
+
import Principal "mo:core/Principal";
333
+
import Runtime "mo:core/Runtime";
334
+
335
+
persistent actor {
336
+
let iiPrincipal =Principal.fromText("rdmx6-jaaaa-aaaaa-aaadq-cai");
format!("Registered {} with email {}", caller, email)
441
+
}
442
+
```
443
+
444
+
</TabItem>
445
+
</Tabs>
446
+
447
+
:::tip[Storing the nonce]
448
+
Mint the nonce in your `registerBegin` (or equivalent) method and persist it in stable memory keyed by the user's principal and the action name. Mark it consumed in`registerFinish` so a bundle cannot be replayed. Use a short freshness window so abandoned attempts age out.
449
+
:::
450
+
227
451
## Local development
228
452
229
453
Start the local network and deploy. With`ii: true`in your `icp.yaml`, icp-cli deploys a local Internet Identity canister automatically:
@@ -291,13 +515,12 @@ To keep principals consistent across your own custom domains, configure **altern
291
515
]
292
516
```
293
517
294
-
3.**On the alternative origin (B):**Set the `derivationOrigin`in your login call to point back to the primary origin:
518
+
3.**On the alternative origin (B):**Set the `derivationOrigin`on the `AuthClient`constructorto point back to the primary origin:
295
519
296
520
```javascript
297
-
authClient.login({
521
+
const authClient = new AuthClient({
298
522
identityProvider:"https://id.ai",
299
523
derivationOrigin:"https://xxxxx.icp0.io", // primary origin A
300
-
onSuccess: () => { /* ... */ },
301
524
});
302
525
```
303
526
@@ -309,11 +532,13 @@ For full details, see the [Internet Identity specification](../../references/int
309
532
310
533
- **Using the wrong II URL per environment**: local development must point to `http://id.ai.localhost:8000`, mainnet to `https://id.ai`. Use the `getIdentityProviderUrl` helper (shown above) to switch based on hostname.
311
534
- **`fetch` "Illegal invocation" in bundled builds**: always pass `fetch: window.fetch.bind(window)` to `HttpAgent.create()`. Without explicit binding, bundlers (Vite, webpack) extract `fetch` from `window` and call it without the correct `this` context.
312
-
- **Missing `onSuccess`/`onError` callbacks**: `authClient.login()` requires both. Without them, login failures are silently swallowed.
535
+
- **Not awaiting `signIn()` or skipping the `try`/`catch`**: `authClient.signIn()` returns a promise that rejects when the user closes the popup or authentication fails. Without `await` and a `catch`, those failures are silently swallowed.
313
536
- **Delegation expiry too long**: the maximum is 30 days. Values above this are silently clamped, causing confusing session behavior. Use 8 hours for typical apps.
314
537
- **Passing principal as a string argument**: the backend reads the caller automatically from the IC protocol. Do not pass it as a function parameter.
315
538
- **Using `shouldFetchRootKey: true` in browser code**: pass `rootKey: canisterEnv?.IC_ROOT_KEY` from `safeGetCanisterEnv()` instead. `shouldFetchRootKey: true` fetches the root key from the replica at runtime, which lets a man-in-the-middle substitute a fake key on mainnet. For Node.js scripts targeting a local replica only, `await agent.fetchRootKey()` is acceptable: but never on mainnet.
316
539
- **Creating multiple `AuthClient` instances**: create one on page load and reuse it. Multiple instances cause race conditions with session storage.
540
+
- **Generating the attribute nonce on the frontend**: a frontend-generated nonce defeats the anti-replay guarantee. The nonce passed to `requestAttributes` must come from a backend canister call so the canister can later verify that the bundle's `implicit:nonce` matches an action it actually started.
541
+
- **Reading attribute data without verifying the signer**: `msg_caller_info_data` (`Prim.callerInfoData` in Motoko) returns whatever bundle the caller provided. The IC system checks the signature, not the identity of the signer. If you skip the `msg_caller_info_signer` check (or compare it against the wrong principal), any canister can mint its own bundle and your method will read attacker-controlled values. Verify the signer matches `rdmx6-jaaaa-aaaaa-aaadq-cai` (Internet Identity) before trusting the bundle.
317
542
318
543
## Next steps
319
544
@@ -325,4 +550,4 @@ For full details, see the [Internet Identity specification](../../references/int
325
550
326
551
{/* TODO: Add Unity native app integration via deep links: see portal native-apps/unity_ii_* */}
0 commit comments