• Stars
    star
    352
  • Rank 120,622 (Top 3 %)
  • Language
    CoffeeScript
  • License
    Apache License 2.0
  • Created over 10 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Node module to abstract away the complexities of the SAML protocol behind an easy to use interface.

Maintenance Notice

This library is currently in maintenance mode. Until further notice, the primary directive is to handle bug reports and security issues with this library.

Any library alternatives and suggestions can be filed under an issue.

SAML2-js

CircleCI

saml2-js is a node module that abstracts away the complexities of the SAML protocol behind an easy to use interface. It achieves this this by helping you implement a service provider for the SAML protocol. It currently does not implement the features to act as an identity provider.

Usage

Install with npm.

  npm install saml2-js --save

Include the SAML library.

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

Documentation

This library exports two constructors.

  • ServiceProvider - Represents a service provider that relies on a trusted IdentityProvider for authentication and authorization in the SAML flow.
  • IdentityProvider - Represents an online service that authenticates users in the SAML flow.

Note: Some options can be set on the SP, IdP, and/or on a per-method basis. For the options that are set in multiple places, they are overridden in the following order: per-method basis overrides IdP which overrides SP.

ServiceProvider(options)

Represents a service provider that relies on a trusted IdentityProvider for authentication and authorization in the SAML flow.

Options

An object that can contain the below options. All options are strings, unless specified otherwise. See note for more information on options.

  • entity_id - Required - Unique identifier for the service provider, often the URL of the metadata file.
  • private_key - Required - (PEM format string) - Private key for the service provider.
  • certificate - Required - (PEM format string) - Certificate for the service provider.
  • assert_endpoint - Required - URL of service provider assert endpoint.
  • alt_private_keys - (Array of PEM format strings) - Additional private keys to use when attempting to decrypt responses. Useful for adding backward-compatibility for old certificates after a rollover.
  • alt_certs - (Array of PEM format strings) - Additional certificates to expose in the SAML metadata. Useful for staging new certificates for rollovers.
  • audience - (String or RegExp) — If set, at least one of the <Audience> values within the <AudienceRestriction> condition of a SAML authentication response must match. Defaults to entity_id.
  • notbefore_skew - (Number) – To account for clock skew between IdP and SP, accept responses with a NotBefore condition ahead of the current time (according to our clock) by this number of seconds. Defaults to 1. Set it to 0 for optimum security but no tolerance for clock skew.
  • force_authn - (Boolean) - If true, forces re-authentication of users even if the user has a SSO session with the IdP. This can also be configured on the IdP or on a per-method basis.
  • auth_context - Specifies AuthnContextClassRef. This can also be configured on a per-method basis.
  • nameid_format - Format for Name ID. This can also be configured on a per-method basis.
  • sign_get_request - (Boolean) - If true, signs the request. This can also be configured on the IdP or on a per-method basis.
  • allow_unencrypted_assertion - (Boolean) - If true, allows unencrypted assertions. This can also be configured on the IdP or on a per-method basis.

Returns the following functions

Example

  var sp_options = {
    entity_id: "https://sp.example.com/metadata.xml",
    private_key: fs.readFileSync("key-file.pem").toString(),
    certificate: fs.readFileSync("cert-file.crt").toString(),
    assert_endpoint: "https://sp.example.com/assert",
    force_authn: true,
    auth_context: { comparison: "exact", class_refs: ["urn:oasis:names:tc:SAML:1.0:am:password"] },
    nameid_format: "urn:oasis:names:tc:SAML:2.0:nameid-format:transient",
    sign_get_request: false,
    allow_unencrypted_assertion: true
  }

  // Call service provider constructor with options
  var sp = new saml2.ServiceProvider(sp_options);

  // Example use of service provider.
  // Call metadata to get XML metatadata used in configuration.
  var metadata = sp.create_metadata();

Service provider function definitions

create_login_request_url(IdP, options, cb)

Get a URL to initiate a login.

Takes the following arguments:

  • IdP - IdP
  • options - An object that can contain the below options. All options are strings, unless specified otherwise. See note for more information on options.
    • relay_state - SAML relay state.
    • auth_context - Specifies AuthnContextClassRef. This can also be configured on the SP.
    • nameid_format - Format for Name ID. This can also be configured on the SP.
    • force_authn- (Boolean) - If true, forces re-authentication of users even if the user has a SSO session with the IdP. This can also be configured on the IdP or SP.
    • sign_get_request - (Boolean) - If true, signs the request. This can also be configured on the IdP or SP.
  • cb(error, login_url, request_id) - Callback called with the login URL and ID of the request.
redirect_assert(IdP, options, cb)

Gets a SAML response object if the login attempt is valid, used for redirect binding.

Takes the following arguments:

  • IdP - IdP
  • options - An object that can contain the below options. All options are strings, unless specified otherwise. See note for more information on options.
    • request_body - (Object) - An object containing the parsed query string parameters. This object should contain the value for either a SAMLResponse or SAMLRequest.
    • allow_unencrypted_assertion - (Boolean) - If true, allows unencrypted assertions. This can also be configured on the IdP or SP.
    • require_session_index - (Boolean) - If false, allow the assertion to be valid without a SessionIndex attribute on the AuthnStatement node.
  • cb(error, response) - Callback called with the request response.
Example of the SAML assert response returned:
{ response_header:
   { id: '_abc-1',
     destination: 'https://sp.example.com/assert',
     in_response_to: '_abc-2' },
  type: 'authn_response',
  user:
   { name_id: 'nameid',
     session_index: '_abc-3',
     attributes:
      { 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname': [ 'Test' ] } } }
post_assert(IdP, options, cb)

Gets a SAML response object if the login attempt is valid, used for post binding.

Takes the following arguments:

  • IdP - IdP
  • options - An object that can contain the below options. All options are strings, unless specified otherwise. See note for more information on options.
    • request_body - (Object) - An object containing the parsed query string parameters. This object should contain the value for either a SAMLResponse or SAMLRequest.
    • allow_unencrypted_assertion - (Boolean) - If true, allows unencrypted assertions. This can also be configured on the IdP or SP.
    • require_session_index - (Boolean) - If false, allow the assertion to be valid without a SessionIndex attribute on the AuthnStatement node.
    • audience - (String or RegExp) — If set, at least one of the <Audience> values within the <AudienceRestriction> condition of a SAML authentication response must match. Defaults to entity_id.
    • notbefore_skew - (Number) – To account for clock skew between IdP and SP, accept responses with a NotBefore condition ahead of the current time (according to our clock) by this number of seconds. Defaults to 1. Set it to 0 for optimum security but no tolerance for clock skew.
  • cb(error, response) - Callback called with the request response.
create_logout_request_url(IdP, options, cb)

Creates a SAML Request URL to initiate a user logout.

Takes the following arguments:

  • IdP - IdP. Note: Can pass sso_logout_url instead of IdP.
  • options - An object that can contain the below options. All options are strings, unless specified otherwise. See note for more information on options.
    • name_id - Format for Name ID. This can also be configured on a per-method basis.
    • session_index - Session index to use for creating logout request.
    • allow_unencrypted_assertion - (Boolean) - If true, allows unencrypted assertions. This can also be configured on the IdP or SP.
    • sign_get_request - (Boolean) - If true, signs the request. This can also be configured on the IdP or SP.
    • relay_state - SAML relay state.
  • cb(error, request_url) - Callback called with the logout request url.
create_logout_response_url(IdP, options, cb)

Creates a SAML Response URL to confirm a successful IdP initiated logout.

Takes the following arguments:

  • IdP - IdP. Note: Can pass sso_logout_url instead of IdP.
  • options - An object that can contain the below options. All options are strings, unless specified otherwise. See note for more information on options.
    • in_response_to - The ID of the request that this is in response to. Should be checked against any sent request IDs.
    • sign_get_request - (Boolean) - If true, signs the request. This can also be configured on the IdP or SP.
    • relay_state - SAML relay state.
  • cb(error, response_url) - Callback called with the logout response url.
create_metadata()

Returns the XML metadata used during the initial SAML configuration.

IdentityProvider(options)

Represents an online service that authenticates users in the SAML flow.

Returns no functions, exists solely to be passed to an SP function.

Options

An object that can contain the below options. All options are strings, unless specified otherwise. See note for more information on options.

  • sso_login_url - Required - Login url to use during a login request.
  • sso_logout_url - Required - Logout url to use during a logout request.
  • certificates - Required - (PEM format string or array of PEM format strings) - Certificate or certificates (array of certificate) for the identity provider.
  • force_authn - (Boolean) - If true, forces re-authentication of users even if the user has a SSO session with the IdP. This can also be configured on the SP or on a per-method basis.
  • sign_get_request - (Boolean) - If true, signs the request. This can also be configured on the [SP or on a per-method basis.
  • allow_unencrypted_assertion - (Boolean) - If true, allows unencrypted assertions. This can also be configured on the SP or on a per-method basis.

Example

  // Initialize options object
  var idp_options = {
    sso_login_url: "https://idp.example.com/login",
    sso_logout_url: "https://idp.example.com/logout",
    certificates: [fs.readFileSync("cert-file1.crt").toString(), fs.readFileSync("cert-file2.crt").toString()],
    force_authn: true,
    sign_get_request: false,
    allow_unencrypted_assertion: false
  };

  // Call identity provider constructor with options
  var idp = new saml2.IdentityProvider(idp_options);

  // Example usage of identity provider.
  // Pass identity provider into a service provider function with options and a callback.
  sp.post_assert(idp, {}, callback);

Example: Express implementation

Library users will need to implement a set of URL endpoints, here is an example of express endpoints.

var saml2 = require('saml2-js');
var fs = require('fs');
var express = require('express');
var app = express();
// If you're using express <4.0:
// var bodyParser = require('body-parser');
// app.use(bodyParser.urlencoded({
//   extended: true
// }));
app.use(express.urlencoded());

// Create service provider
var sp_options = {
  entity_id: "https://sp.example.com/metadata.xml",
  private_key: fs.readFileSync("key-file.pem").toString(),
  certificate: fs.readFileSync("cert-file.crt").toString(),
  assert_endpoint: "https://sp.example.com/assert"
};
var sp = new saml2.ServiceProvider(sp_options);

// Create identity provider
var idp_options = {
  sso_login_url: "https://idp.example.com/login",
  sso_logout_url: "https://idp.example.com/logout",
  certificates: [fs.readFileSync("cert-file1.crt").toString(), fs.readFileSync("cert-file2.crt").toString()]
};
var idp = new saml2.IdentityProvider(idp_options);

// ------ Define express endpoints ------

// Endpoint to retrieve metadata
app.get("/metadata.xml", function(req, res) {
  res.type('application/xml');
  res.send(sp.create_metadata());
});

// Starting point for login
app.get("/login", function(req, res) {
  sp.create_login_request_url(idp, {}, function(err, login_url, request_id) {
    if (err != null)
      return res.send(500);
    res.redirect(login_url);
  });
});

// Variables used in login/logout process
var name_id, session_index;

// Assert endpoint for when login completes
app.post("/assert", function(req, res) {
  var options = {request_body: req.body};
  sp.post_assert(idp, options, function(err, saml_response) {
    if (err != null)
      return res.send(500);

    // Save name_id and session_index for logout
    // Note:  In practice these should be saved in the user session, not globally.
    name_id = saml_response.user.name_id;
    session_index = saml_response.user.session_index;

    res.send("Hello #{name_id}! session_index: #{session_index}.");
  });
});

// Starting point for logout
app.get("/logout", function(req, res) {
  var options = {
    name_id: name_id,
    session_index: session_index
  };

  sp.create_logout_request_url(idp, options, function(err, logout_url) {
    if (err != null)
      return res.send(500);
    res.redirect(logout_url);
  });
});

app.listen(3000);

More Repositories

1

microplane

A CLI tool to make git changes across many repos, especially useful with Microservices.
Go
367
star
2

csvlint

library and command line tool that validates a CSV file
Makefile
186
star
3

sphinx

Configurable HTTP rate limiter
Go
164
star
4

leakybucket

Leaky bucket implementation in Go with support for different backends (redis, in-memory)
Go
85
star
5

wag

sWAGger - Web API Generator
Go
77
star
6

gitbot

programmatically make changes to many git repositories
Makefile
74
star
7

dev-handbook

A guide to the processes, conventions, and philosophies of the Clever dev team.
Makefile
63
star
8

moredis

sync data from mongo into redis
Go
53
star
9

ARCHIVED-mongo-graph

visualize mongo data
CoffeeScript
40
star
10

optimus

Concurrently extract, transform, and load tables of data in Go
Go
34
star
11

quest

node http requests made easy
CoffeeScript
29
star
12

underscore.deep

Underscore utilities for operating on nested objects
CoffeeScript
27
star
13

http-science

Forward http requests to two places, report any differences in the response.
Go
27
star
14

clever-ruby

Clever Ruby library
Ruby
27
star
15

clever-python

Clever Python bindings
Python
27
star
16

resolve-ip

service that takes in an IP address and converts it to a latitude and longitude
Go
25
star
17

components

Frontend components
TypeScript
24
star
18

clever-js

Node.js library for the Clever API
CoffeeScript
24
star
19

workflow-manager

Minimal Workflow orchestrator for AWS Step Functions
Go
24
star
20

reposync

Syncs repos for a GitHub user or organization into a folder on your computer
Makefile
23
star
21

clever-php

Clever PHP library
PHP
22
star
22

thrift-pool

A module that wraps thrift interfaces in connection pooling logic to make them more resilient.
CoffeeScript
22
star
23

gitsem

a command line utility for managing semantically versioned (semver) git tags
Makefile
18
star
24

terrafam

IAM modules and YML-based terraform configuration generator
HCL
18
star
25

log-replay

Replays log files at a given speed
Makefile
16
star
26

amazon-kinesis-client-go

Amazon Kinesis Client for Go
Go
16
star
27

ARCHIVED-mongoose-repl

A Mongo REPL with the full power of Mongoose
CoffeeScript
16
star
28

sfncli

Utility to create AWS Step Function activities out of command line programs
Go
15
star
29

ARCHIVED-json-schema-converter

Utilities to translate your schema into anything, as long as 'anything' is JSON Schema.
CoffeeScript
15
star
30

policies

Clever Terms and Policies
14
star
31

pathio

go library for transparently writing to and reading from different types of paths (supports stdout, s3, and fs)
Go
14
star
32

ios-sdk

Clever iOS SDK
Objective-C
13
star
33

discovery-go

Programmatically find services
Go
13
star
34

clever-go

Go library for the Clever API
Go
13
star
35

writable-stream-parallel

Parallelize your _write()s
JavaScript
12
star
36

go-bench

HTTP benchmarking with customizable log replays written in go
Go
12
star
37

node-google-admin-sdk

node.js library for Google's Admin SDK
CoffeeScript
12
star
38

unix-sort

Sort large streams of JSON objects using the unix sort command.
CoffeeScript
12
star
39

ARCHIVED-ebs-snapshots

Service to automate creation and cleanup of Amazon EBS snapshots
Python
11
star
40

graphviz-service

A REST interface to the graphviz command line tool.
Makefile
9
star
41

clever-oauth-examples

DEPRECATED - this repository is no longer maintained
PHP
8
star
42

marathon-stats

ARCHIVED: A simple container which queries marathon and mesos for stats about their current state, and logs these stats to stderr
Go
7
star
43

tracing-middleware

Moved to opentracing-contrib org
JavaScript
7
star
44

mesos-visualizer

Visualizations showing mesos resource utilization
Go
7
star
45

stealth

Go wrapper for credstash secret store
Go
7
star
46

sentry-node

simple node wrapper around the Sentry API
CoffeeScript
6
star
47

understream

stream all the things
CoffeeScript
6
star
48

kayvee-go

Logs for human and machine readability
Go
6
star
49

unix-join

Join large streams of JSON objects using the unix join command.
CoffeeScript
6
star
50

loofah

Data scrubber
CoffeeScript
5
star
51

swagger-api

A Swagger Definition for the Clever API
Go
5
star
52

analytics-monitor

watch over our db to ensure up-to-date data
Go
5
star
53

flarebot

A bot for controlling Flares
Go
5
star
54

csvutil

A [un]marshaling utility for translating between CSV data and Go structs
Go
5
star
55

node-redis-reservation

Distributed locking mechanism built on redis.
CoffeeScript
5
star
56

omniauth-clever

Ruby
5
star
57

clever-cli

DEPRECATED - this repository is no longer maintained
Go
4
star
58

ARCHIVED-baseworker-go

A simple Gearman worker library
Go
4
star
59

frontend-boilerplate

Want to create a React app? Start here!
JavaScript
4
star
60

ecs-rollover

DEPRECATED: script to safely rollover ECS nodes without service interruption
Python
4
star
61

clever-csharp

C# client library for Clever APIs
C#
3
star
62

ARCHIVED-oplog-replay

Replay mongodb oplogs at variable speed
Go
3
star
63

discovery-node

Programmatically find services (like discovery-go, but for node)
TypeScript
3
star
64

ci-scripts

Re-usable continuous integration (CI) scripts
Shell
3
star
65

kayvee

Kayvee translates an object into a human and machine parseable string
3
star
66

ddb-to-es

Process DynamoDB streams and INDEX, MODIFY, DELETE Elasticsearch document
Go
3
star
67

go-utils

collection of small packages with useful, common behavior
Go
3
star
68

clever-java

Java library for the Clever API
Java
2
star
69

prune-images

a worker that prunes old images from ECR and Docker Hub
Makefile
2
star
70

ecs-task-metadata-exporter

A Prometheus exporter for monitoring ECS containers using the ECS task metadata endpoint.
Go
2
star
71

mongo-lock-go

Distributed lock client backed by mongo
Go
2
star
72

ARCHIVED-go-validation

Go validation library
Go
2
star
73

kayvee-python

Kayvee translates an dictionary into a human and machine parseable string
Python
2
star
74

dynamodb-lock-go

Go client library for distributed locking using a DynamoDB backend
Go
1
star
75

mongo-lock-node

Implements a distributed lock client backed by mongo
TypeScript
1
star
76

atlas-api-client

Go client for MongoDB Atlas
Go
1
star
77

whackanop

periodically kill long-running mongo operations
Makefile
1
star
78

ARCHIVED-redirector

simple redirection app to redirect from one domain to another, preserving protocol, subdomain, path, and querystring
CoffeeScript
1
star
79

elasticsearch-toolbox

Maintenance tooling for Elasticsearch
TypeScript
1
star
80

async-ext

Extensions to the Node.js async library
CoffeeScript
1
star
81

connect-session-compress

connect session store that compresses the session data. compatible with any backing store (redis, dynamo, etc.)
JavaScript
1
star
82

consul-service-pulse

Externally confirms if consul services are alive. Used to cleanup stale consul nodes, and better understand networking errors.
Go
1
star
83

ARCHIVED-mongoose-any-index

Extra index functionality for mongoose
CoffeeScript
1
star
84

talks

slides!
Go
1
star
85

kayvee-js

Package kayvee provides methods to output human and machine parseable strings
TypeScript
1
star
86

python-redis-reservation

Python library for resource reservation using Redis
Python
1
star
87

json-predicate-transformer

A simple utility for modifying JSON objects using a predicate-transformer paradigm
TypeScript
1
star
88

discovery-python

Programmatically find service endpoints (i.e. discovery-go for python)
Python
1
star
89

go-process-metrics

A library for tracking golang process metrics
Makefile
1
star