如何解决如何通过 Hyperledger 结构中的快速 REST API 注册客户端 /api/v1/register/api/v1/login/api/v1/invoke
我想通过 REST API 注册应用程序的用户。我已经通过 enrollAdmin.js 和 registerUser.js 函数注册了管理员和用户,但我想通过节点 SDK 调用这些函数并使用用户名(UUID)动态注册用户) 使其完全匿名。
作为用户名,我想创建一个唯一的 UUID 并将其保存在世界状态中,同时将该 UUID 与密码和姓名等个人信息一起保存在链下数据库中,以便我可以将个人信息与 UUID 相关联。
没错,我对注册新用户必须执行的所有不同步骤感到困惑:
我必须按照什么顺序来注册和注册用户?它们都应该在 express API 还是在链码中定义?
这是我创建 REST Api 的第一种方法,到目前为止我只定义了布局、连接配置文件和钱包。
如果有人可以帮助我在 express REST API 中实现注册过程,以便将 UUID 的身份保存在世界状态中,我将不胜感激。
提前致谢。
- server.js
'use strict';
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
// Setting for Hyperledger Fabric
const { Wallets,FileSystemWallet,Gateway } = require('fabric-network');
const path = require('path');
const fs = require('fs');
const channelName = 'mychannel';
const mspOrg1 = 'Org1MSP';
const walletPath = path.join(__dirname,'..','wallet');
const ccpPath = path.resolve(__dirname,'connection-org1.json');
//register
app.post('/api/register',async function (req,res) {
try{
// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(),'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
} catch (error) {
}
});
//login
app.post('/api/login','wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
} catch (error) {
}
});
app.listen(3000,()=>{
console.log("***********************************");
console.log("API server listening at localhost:3000");
console.log("***********************************");
});
解决方法
实现您想要的样子的过程很简单。中间使用链下数据库作为映射表。我只写了核心流程逻辑。
/api/v1/register
-
验证检查
验证用户id唯一,缺少所需信息值,正则表达式正确,没有错误信息。 -
生成随机UUID
首先创建一个随机的、唯一的 uuid。npm/uuid
const UUID = uuid.v4();
- 注册/注册用户到fabric-ca
以结构用户的身份执行注册过程。进入这个过程的信息是UUID,用户的信息不会存储在区块链中。fabricUser
是新创建的类,通过 Enroll 方法执行 Fabric 用户注册和注册过程后返回结果。
enrollment = await fabricUser.Enroll(UUID);
await wallet.put(enrollment);
- 插入数据库
在数据库中保存用户信息的同时,通过存储上面创建的UUID来映射它。 数据库是作为示例创建的,假设mongodb
。
db.collection('User').insertOne({
'uuid': UUID,'user_id': <input_user_id>,...
});
/api/v1/login
登录流程如下。 我不知道您要使用哪种身份验证/身份验证方法,因此我将假设基于 auth 2.0 的令牌身份验证方法。
-
验证登录所需信息的有效性以及是否有错误信息。
-
获取 UUID
generateAuthToken
是一个生成JWT
的新函数。
let res = await db.collection("User").findOne({'user_id': `<input_user_id>` });
return generateAuthToken(res.uuid);
/api/v1/invoke
Fabric 资源请求流程如下。
-
令牌验证和资源授权检查
-
从
userName
获取token
getPayload
是一个函数,用于从令牌中获取位于第 1 个索引处的负载值。
const rawPayload = getPayload(token);
const jsonPayload = JSON.parse(rawPayload);
return jsonPayload
- 获取钱包并调用链码
fabricChaincode
是一个封装了fabric-sdk 调用过程的函数。它是一个通过输入身份、链码信息和参数来执行调用并返回结果的函数。
const user = await db.collection("User").findOne({'user_id': jsonPayload.user_id });
const fabricIdentity = await wallet.get(user.uuid);
const res = fabricChaincode.invoke(fabricIdentity,`<your_chaincode_info>`,`<input_chaincode_params>`)
return res;
[编辑]
添加它以供您理解。
fabricUser.js
/*
* Copyright IBM Corp. All Rights Reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
'use strict';
const { Wallets } = require('fabric-network');
const FabricCAServices = require('fabric-ca-client');
const fs = require('fs');
const path = require('path');
async function Enroll(user_id) {
try {
// load the network configuration
const ccpPath = path.resolve(__dirname,'..','test-network','organizations','peerOrganizations','org1.example.com','connection-org1.json');
const ccp = JSON.parse(fs.readFileSync(ccpPath,'utf8'));
// Create a new CA client for interacting with the CA.
const caURL = ccp.certificateAuthorities['ca.org1.example.com'].url;
const ca = new FabricCAServices(caURL);
// Create a new file system based wallet for managing identities.
const walletPath = path.join(process.cwd(),'wallet');
const wallet = await Wallets.newFileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
// Check to see if we've already enrolled the user.
const userIdentity = await wallet.get(user_id);
if (userIdentity) {
console.log(`An identity for the user ${user_id} already exists in the wallet`);
return;
}
// Check to see if we've already enrolled the admin user.
const adminIdentity = await wallet.get('admin');
if (!adminIdentity) {
console.log('An identity for the admin user "admin" does not exist in the wallet');
console.log('Run the enrollAdmin.js application before retrying');
return;
}
// build a user object for authenticating with the CA
const provider = wallet.getProviderRegistry().getProvider(adminIdentity.type);
const adminUser = await provider.getUserContext(adminIdentity,'admin');
// Register the user,enroll the user,and import the new identity into the wallet.
const secret = await ca.register({
affiliation: 'org1.department1',enrollmentID: user_id,role: 'client'
},adminUser);
const enrollment = await ca.enroll({
enrollmentID: user_id,enrollmentSecret: secret
});
const x509Identity = {
credentials: {
certificate: enrollment.certificate,privateKey: enrollment.key.toBytes(),},mspId: 'Org1MSP',type: 'X.509',};
await wallet.put(user_id,x509Identity);
console.log(`Successfully registered and enrolled admin user ${user_id} and imported it into the wallet`);
} catch (error) {
console.error(`Failed to register user ${user_id}: ${error}`);
process.exit(1);
}
}
module.exports = {
Enroll
}
api.js
const uuid = require('uuid');
const fabricUser = require('./fabricUser);
const UUID = uuid.v4();
let res = await fabricUser.Enroll(UUID);
console.log(res);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。