You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于为Hyperledger Composer Rest Server实现本地Passport策略的技术咨询

Great question! Implementing a local Passport strategy for the Hyperledger Composer REST Server is totally doable—here's a step-by-step breakdown of the architecture and configuration to make it work without third-party auth services:

整体架构思路

The core components you'll need to wire together are:

  • Local User Database: A store (like MongoDB, PostgreSQL, or even a simple JSON file) to keep user credentials (hashed passwords, usernames) and their associated Hyperledger Composer participant IDs.
  • Passport Local Strategy: The Passport.js strategy that handles username/password authentication against your local database.
  • Custom Auth Middleware: A layer that integrates the Passport strategy with the Composer REST Server, handling login sessions and mapping authenticated users to Composer participants.
  • Composer Participant Mapping: A way to link your local user records to existing participants on the Hyperledger Fabric network (so the REST server knows which participant to act as for authenticated requests).
具体配置步骤

1. Set Up Your Local User Store

First, create a database to store your users. For example, with MongoDB:

  • Create a users collection with fields like:
    • username (unique identifier for login)
    • passwordHash (never store plaintext passwords—use bcrypt to hash them)
    • participantId (the ID of the corresponding Composer participant, e.g., org.example.User#user123)

2. Install Required Dependencies

In your project directory, install the necessary packages:

npm install passport passport-local bcryptjs mongoose express-session
  • passport & passport-local: Handle the local authentication logic
  • bcryptjs: Securely hash and verify passwords
  • mongoose: (Optional) If using MongoDB for user storage
  • express-session: Manage user sessions after login

3. Implement the Passport Local Strategy

Create a file (e.g., passport-config.js) to define your strategy:

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcryptjs');
const User = require('./models/User'); // Your Mongoose user model

passport.use(new LocalStrategy((username, password, done) => {
  // Find the user in your local database
  User.findOne({ username: username })
    .then(user => {
      if (!user) {
        return done(null, false, { message: 'Incorrect username' });
      }
      // Verify the password hash
      bcrypt.compare(password, user.passwordHash, (err, isMatch) => {
        if (err) throw err;
        if (isMatch) {
          return done(null, user);
        } else {
          return done(null, false, { message: 'Incorrect password' });
        }
      });
    })
    .catch(err => done(err));
}));

// Serialize/deserialize user for session management
passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  User.findById(id, (err, user) => {
    done(err, user);
  });
});

module.exports = passport;

4. Integrate with Composer REST Server

Instead of using the default composer-rest-server command directly, create a custom Express server that wraps the Composer REST API and adds your Passport auth:

  1. Create a file like server.js:
const express = require('express');
const session = require('express-session');
const passport = require('./passport-config');
const composerRestServer = require('composer-rest-server');

const app = express();

// Configure session management
app.use(session({
  secret: 'your-secret-key-here', // Use a secure secret in production
  resave: false,
  saveUninitialized: false
}));

// Initialize Passport
app.use(passport.initialize());
app.use(passport.session());

// Add login endpoint
app.post('/login', passport.authenticate('local'), (req, res) => {
  // On successful login, send back user info (including participantId)
  res.json({
    username: req.user.username,
    participantId: req.user.participantId
  });
});

// Configure Composer REST Server options
const restServerOptions = {
  card: 'admin@your-network', // Your admin card
  businessNetworkName: 'your-network-name',
  auth: {
    // Tell the REST server to use our custom auth middleware
    middleware: (req, res, next) => {
      // Check if user is authenticated
      if (!req.isAuthenticated()) {
        return res.status(401).send('Unauthorized');
      }
      // Set the user's participant ID for the Composer request
      req.composer = {
        participantId: req.user.participantId
      };
      next();
    }
  },
  // Other REST server options (port, cors, etc.)
  port: 3000,
  cors: true
};

// Start the Composer REST Server
composerRestServer(app, restServerOptions);

// Start the Express server
app.listen(restServerOptions.port, () => {
  console.log(`Composer REST Server with local auth running on port ${restServerOptions.port}`);
});
  1. Run your custom server:
node server.js

5. Map Users to Composer Participants

Make sure every local user has a corresponding participant in your Hyperledger Composer business network. For example, if your network has an org.example.User participant type, create a participant entry for each user with the same participantId stored in your local database.

Key Notes & Best Practices
  • Password Security: Always hash passwords with bcrypt (or similar) before storing them—never store plaintext passwords.
  • Session Security: In production, use a secure session store (like connect-mongo) instead of the default memory store, and use HTTPS to encrypt traffic.
  • Error Handling: Add proper error handling for database failures, invalid credentials, and missing participant mappings.
  • Authorization: After authentication, you can add additional middleware to enforce role-based access control (RBAC) based on the user's participant type.

内容的提问来源于stack exchange,提问作者MrL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:42:16