使用React实现互联网身份的教程

huangapple go评论52阅读模式
英文:

Tutorials for the Implementation of Internet Identity with React

问题

我是智能合约开发的新手,也是 IC(互联网计算)开发的新手。我已经按照 Motoko 教程和 IC 开发介绍进行了学习。我的下一步是使用 Internet Identity 实现一个简单的登录表单(带有 React 界面)。

我查看了一些教程,但并不令人满意,然后我找到了这个 GitHub 仓库:https://github.com/krpeacock/auth-client-demo 但只运行 dfx 部署时,我遇到了这个错误:

Stderr:
Building canisters before generate for 
Motoko
Shrink WASM module size.
Generating type declarations for canister 
whoami:
  src/declarations/whoami/whoami.did.d.ts
  src/declarations/whoami/whoami.did.js
  src/declarations/whoami/whoami.did
sh: webpack: command not found

实际上,我只需要一个良好的起始示例,没有错误,以指导我使用 React 作为前端实现本地 Internet Identity。有没有一些好的起始仓库?

英文:

I am new to smart-contract development and also new to IC development.
I have already followed the motoko tutorials and the introduction to development in IC. My next step was to implement a simple login form (with a react interface) using Internet Identity.

I looked at some tutorials, which were not very satisfying and I came across this repository on github: https://github.com/krpeacock/auth-client-demo but just running the dfx deployment I got this error:

Stderr:
Building canisters before generate for 
Motoko
Shrink WASM module size.
Generating type declarations for canister 
whoami:
  src/declarations/whoami/whoami.did.d.ts
  src/declarations/whoami/whoami.did.js
  src/declarations/whoami/whoami.did
sh: webpack: command not found

In fact, I just need a good start example, without errors, to guide me to implement the local Internet identity with react as a frontend.

Are there any good repositories to start with?

答案1

得分: 0

任何人遇到困难,这里有一个带有多个框架的工作示例:

https://github.com/krpeacock/auth-client-demo

特别是,您现在可以添加:

```json
    "internet_identity": {
      "type": "custom",
      "candid": "https://github.com/dfinity/internet-identity/releases/latest/download/internet_identity.did",
      "wasm": "https://github.com/dfinity/internet-identity/releases/latest/download/internet_identity_dev.wasm.gz",
      "shrink": false,
      "remote": {
        "candid": "internet_identity.did",
        "id": {
          "ic": "rdmx6-jaaaa-aaaaa-aaadq-cai"
        }
      },
    },

将其添加到您的 dfx.json 中,以便将其包含在您自己的项目中,同时在部署时,它还将在本地复制品(“本地测试网”)和主网之间自动解析。然后,通过添加 @dfinity/auth-client 依赖项,您可以在前端添加必要的逻辑:

import { AuthClient } from '@dfinity/auth-client';
// 这些是由 dfx 从您的后端 canister 代码生成的,因此您可以在前端环境(或其他地方)实例化一个“后端” canister 实例。
import { canisterId, createActor } from "../../../declarations/backend";

// 假设 index.html 正在加载并进行脚本调用:

async function init() {
  const authClient = await AuthClient.create({/*options can go here */});
  const loginButton = document.getElementById("login-button");

  loginButton.onclick = () => {
    authClient.login({
      identityProvider:
        process.env.DFX_NETWORK === "ic"
        ? "https://identity.ic0.app/#authorize"
        : `http://localhost:4943?canisterId=${process.env.CANISTER_ID_INTERNET_IDENTITY}#authorize`,
      onSuccess: async () => {
        handleAuthenticated(authClient);
      },
    });
  };
};

// other initialization code, etc

init();

// other initialization code, etc

async function handleAuthenticated(authClient) {
  // 获取经过身份验证的用户在 IndexDb 中存储的身份(可以获取主体,它是公钥的 ~hash)以显示给用户等。
  const identity = (await authClient.getIdentity());
  // 现在,经过身份验证的身份可用于创建后端 canister 的实例:
  const backend = createActor(canisterId, {
    agentOptions: {
      identity,
    },
  });
  // 此后端实例现在将具有非匿名的“调用者”,而不是用户的身份。
  const result = await backend.makeSomeCallLikeHelloWorldOrCRUDOrMintOrSendBtcEtc(). 
  // 相应地更新 UI...
  updateUi(result);
}

请注意,如果使用 Vite,则可能需要使用 import.meta.env 而不是 process.env;只需验证您的项目的环境变量是否配置正确。


<details>
<summary>英文:</summary>

Anyone gets stuck, here&#39;s a working example with multiple frameworks:

https://github.com/krpeacock/auth-client-demo

In particular, you can now add:


```json
    &quot;internet_identity&quot;: {
      &quot;type&quot;: &quot;custom&quot;,
      &quot;candid&quot;: &quot;https://github.com/dfinity/internet-identity/releases/latest/download/internet_identity.did&quot;,
      &quot;wasm&quot;: &quot;https://github.com/dfinity/internet-identity/releases/latest/download/internet_identity_dev.wasm.gz&quot;,
      &quot;shrink&quot;: false,
      &quot;remote&quot;: {
        &quot;candid&quot;: &quot;internet_identity.did&quot;,
        &quot;id&quot;: {
          &quot;ic&quot;: &quot;rdmx6-jaaaa-aaaaa-aaadq-cai&quot;
        }
      },
    },

To your dfx.json to include it in your own project, while it will also automatically resolve between your local replica ("local testnet") and mainnet when deploying. Then by adding the @dfinity/auth-client dependency, you can then add the necessary logic to your frontend:

import { AuthClient } from &#39;@dfinity/auth-client&#39;;
// These are generated by dfx from your backend canister code so you can instantiate a &quot;backend&quot; canister instance in your frontend environment (or wherever else).
import { canisterId, createActor } from &quot;../../../declarations/backend&quot;;

// Assuming index.html is loading and makes the script call:

async function init() {
  const authClient = await AuthClient.create({/*options can go here */});
  const loginButton = document.getElementById(&quot;login-button&quot;);

  loginButton.onclick = () =&gt; {
    authClient.login({
      identityProvider:
        process.env.DFX_NETWORK === &quot;ic&quot;
        ? &quot;https://identity.ic0.app/#authorize&quot;
        : `http://localhost:4943?canisterId=${process.env.CANISTER_ID_INTERNET_IDENTITY}#authorize`,
      onSuccess: async () =&gt; {
        handleAuthenticated(authClient);
      },
    });
  };
};

// other initialization code, etc

init();

// other initialization code, etc

async function handleAuthenticated(authClient) {
  // Gets the identity of the authenticated user as its stored in IndexDb 
  // (can get the principal, which is ~hash of public key) to display it the user, etc. 
  const identity = (await authClient.getIdentity());
  // Now the authenticated identity can be used to create an instance of the backend canister:
  const backend = createActor(canisterId, {
    agentOptions: {
      identity,
    },
  });
  // This backend instance will now have a `caller` that&#39;s not anonymous, but of the user.
  const result = await backend.makeSomeCallLikeHelloWorldOrCRUDOrMintOrSendBtcEtc(). 
  // Update the ui accordingly...
  updateUi(result);
}

Note if using Vite, you'll want to probably use import.meta.env instead of process.env; just verify you've got your project's environmental variables configured correctly.

huangapple
  • 本文由 发表于 2023年4月17日 05:16:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76030373.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定