Quick Start
This guide offers a simple example of how to use the @icp-sdk/auth package to authenticate a user with Internet Identity on an Internet Computer web app.
In a web application, you can use the package in this way:
import { AuthClient } from '@icp-sdk/auth/client';import { HttpAgent } from '@icp-sdk/core/agent';import { AttributesIdentity } from '@icp-sdk/core/identity';import { Principal } from '@icp-sdk/core/principal';
const authClient = new AuthClient({ identityProvider: { authorizeUrl: process.env.II_AUTHORIZE_URL, canisterId: process.env.II_CANISTER_ID, },});
// Check for an existing session (synchronous)if (authClient.isAuthenticated()) { const identity = await authClient.getIdentity(); console.log('Restored session:', identity.getPrincipal().toString());}
// sign in and request attributes in parallelconst signInPromise = authClient.signIn();const attributesPromise = authClient.requestAttributes({ keys: ['email', 'name'], nonce: () => fetchNonceFromYourBackend(), // () => Promise<Uint8Array>});
await signInPromise;const { data, signature } = await attributesPromise;
// wrap the identity with attributes so canister calls include sender_infoconst identity = await authClient.getIdentity();const identityWithAttributes = new AttributesIdentity({ inner: identity, attributes: { data, signature }, signer: { canisterId: Principal.fromText(process.env.II_CANISTER_ID) },});
const agent = await HttpAgent.create({ identity: identityWithAttributes });
// this call will include the signed attributesawait agent.call(appCanisterId, { methodName: 'greet', arg: IDL.encode([IDL.Text], ['world']),});
// later in your appawait authClient.signOut();Next Steps
Section titled “Next Steps”Check out the Integrating Internet Identity guide for a more detailed guide on how to integrate Internet Identity into your web app.
For a full example, check out the Who Am I example.