关于为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
userscollection 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 logicbcryptjs: Securely hash and verify passwordsmongoose: (Optional) If using MongoDB for user storageexpress-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:
- 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}`); });
- 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.
- 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

