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

如何使用Samling等免费IdP测试saml2-js?SAML新手SP开发问询

Building a Node.js SAML Service Provider (SP) with saml2-js and a Free IdP

Hey there! Since you're new to SAML and looking to build a Node.js SP using saml2-js with a free IdP like Samling, let's walk through this step by step to make it straightforward and manageable.

Prerequisites

  • Node.js installed on your machine
  • A free account with an IdP like Samling (you’ll need their metadata URL/XML for configuration)
  • Basic familiarity with Express.js (we’ll use it to handle HTTP requests for the login flow)

Step 1: Set Up Dependencies

First, initialize your project and install the required packages:

mkdir saml-sp-demo && cd saml-sp-demo
npm init -y
npm install saml2-js express

Step 2: Configure SP and IdP

First, log into your Samling account to get the IdP metadata (usually an XML file or public URL). Then create a config.js file to define your SP and IdP objects:

const saml2 = require('saml2-js');

// Service Provider (SP) configuration
const sp_options = {
  entity_id: "http://localhost:3000/saml/metadata", // Your SP's unique identifier (matches metadata URL)
  private_key: "<YOUR_SP_PRIVATE_KEY>", // Generate a private key for your SP (see note below)
  certificate: "<YOUR_SP_CERTIFICATE>", // Corresponding public certificate
  assert_endpoint: "http://localhost:3000/saml/assert" // Callback URL where IdP sends responses
};

// Identity Provider (IdP) configuration (pulled from Samling metadata)
const idp_options = {
  sso_login_url: "<SAMLING_SSO_LOGIN_URL>", // Login endpoint from Samling metadata
  sso_logout_url: "<SAMLING_SSO_LOGOUT_URL>", // Optional, for logout flows
  certificates: ["<SAMLING_PUBLIC_CERT>"] // Samling's public cert to verify response signatures
};

// Initialize SP and IdP instances
const sp = new saml2.ServiceProvider(sp_options);
const idp = new saml2.IdentityProvider(idp_options);

module.exports = { sp, idp };

Note: To generate a private key and certificate for your SP, use OpenSSL in your terminal:

openssl req -x509 -newkey rsa:4096 -keyout sp-private-key.pem -out sp-certificate.pem -days 365 -nodes

Step 3: Implement the Authentication Flow

Create an app.js file to handle login initiation, IdP callbacks, and metadata serving:

const express = require('express');
const { sp, idp } = require('./config');
const app = express();

// Parse incoming request bodies
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// Route to start the SAML login flow
app.get('/login', (req, res) => {
  const options = {
    relay_state: req.query.redirect || '/' // Where to redirect post-authentication
  };
  sp.create_login_request_url(idp, options, (err, login_url, request_id) => {
    if (err) return res.status(500).send('Failed to create login request');
    // In production, store request_id in a session to validate later (use express-session)
    res.redirect(login_url);
  });
});

// Callback route to process IdP's SAML response
app.post('/saml/assert', (req, res) => {
  const options = {
    request_body: req.body
    // Optional: Add request_id here to validate the request matches the one you sent
  };
  sp.post_assert(idp, options, (err, saml_response) => {
    if (err) return res.status(500).send('Failed to process SAML assertion');
    // saml_response.user contains the authenticated user's attributes
    console.log('Authenticated user:', saml_response.user);
    // In production, set a session cookie to track the logged-in user
    res.redirect(saml_response.relay_state || '/');
  });
});

// Serve SP metadata (required for IdP to recognize your SP)
app.get('/saml/metadata', (req, res) => {
  res.type('application/xml');
  res.send(sp.create_metadata());
});

// Test landing page
app.get('/', (req, res) => {
  res.send('Welcome! <a href="/login">Login with SAML</a>');
});

// Start the server
app.listen(3000, () => {
  console.log('SP server running at http://localhost:3000');
});

Step 4: Configure the IdP (Samling)

  • Log into your Samling account and add a new Service Provider
  • Use your SP's metadata URL (http://localhost:3000/saml/metadata) to auto-configure, or manually enter the entity ID and assert endpoint
  • Upload your SP's certificate (sp-certificate.pem) so Samling can sign responses for your SP

Step 5: Test the Flow

  1. Start your server: node app.js
  2. Visit http://localhost:3000 and click "Login with SAML"
  3. You’ll be redirected to Samling’s login page; enter your credentials
  4. After successful authentication, you’ll be sent back to your app, and the user’s info will appear in your terminal

Beginner Tips

  • Always validate SAML responses: saml2-js handles this by default, but double-check you’re using the correct IdP certificate
  • Use express-session in production to track authenticated users securely
  • If you hit signature validation errors, verify that your SP’s private key/certificate and Samling’s public cert are correctly formatted and entered
  • Explore the saml2-js docs for advanced features like single logout or custom attribute mapping

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:08:09