Skip to content

PolicyAgent

Zoltan Tarcsay edited this page Dec 2, 2016 · 10 revisions

PolicyAgent

Kind: global class
Mixes: {events~EventEmitter}

new PolicyAgent(options)

Param Type Default Description
options object
options.serverUrl string The deployment URI of the OpenAM server, e.g. http://openam.example.com:8080/openam
options.username string Agent username (needed for certain operations, e.g. policy decision requests)
options.password string Agent password (needed for certain operations, e.g. policy decision requests)
options.realm string "/" Agent realm (needed for certain operations, e.g. policy decision requests)
[options.appUrl] string The root URL of the application, e.g. http://app.example.com:8080 (required for notifications)
options.errorPage function Callback function; If present, the function's return value will be sent as an error page, otherwise the default error template will be used. The function will be called with a context object as the argument.
[options.logger] winston~Logger new Logger() A winstonjs logger instance. If undefined, a new Console logger is created.
[options.logLevel] string "error" logging level: see winston's documentation; only used when logger is undefined.
[options.sessionCache] Cache Custom session cache object (if undefined, a SimpleCache instance will be created with an expiry time of 5 minutes)
[options.openAMClient] OpenAMClient | * new OpenAMClient() Custom OpenAMClient object (mostly for testing purposes)

Example

var express = require('express'),
    openamAgent = require('openam-agent')
    MemcachedCache = require('openam-agent-cache-memcached'),
    PolicyAgent = openamAgent.PolicyAgent,
    CookieShield = openamAgent.CookieShield;

var config = {
   serverUrl: 'http://openam.example.com:8080/openam',
   appUrl: 'http://app.example.com:8080',
   notificationRoute: '/',
   notificationsEnabled: true,
   username: 'my-agent',
   password: 'changeit',
   realm: '/',
   logLevel: 'info',
   cache: new MemcachedCache({url: 'localhost:11211', expiresAfterSeconds: 600}),
   errorPage: function (status, message, details) {
       return '<html><body><h1>' + status + ' - '  + message + '</h1></body></html>'
   }
};

var agent = new PolicyAgent(config);
var app = express();

app.use(agent.shield(new CookieShield()));
app.use('/foo/bar/baz', agent.notifications);

app.listen(8080);

policyAgent.options : object

Config options

Kind: instance property of PolicyAgent

policyAgent.id : string

Short random ID that lets you differentiate agents in logs, etc.

Kind: instance property of PolicyAgent

policyAgent.paths : object

Built in routes (cdsso, notifications)

Kind: instance property of PolicyAgent

policyAgent.openAMClient : * | OpenAMClient

OpenAM client used by the agent and its shields

Kind: instance property of PolicyAgent

policyAgent.logger : winston~Logger | *

Logger

Kind: instance property of PolicyAgent

policyAgent.sessionCache : * | SimpleCache

Session cache

Kind: instance property of PolicyAgent

policyAgent.serverInfo : Promise

Empty Promise (Server info is loaded when init() is called)

Kind: instance property of PolicyAgent

policyAgent.agentSession : Promise

The agent's own OpenAM session. It will only get created when it is needed by some request.

Kind: instance property of PolicyAgent

policyAgent.errorTemplate : function

Compiled Handlebars error page template

Kind: instance property of PolicyAgent

policyAgent.init()

Initializes the agent (gets server info)

Kind: instance method of PolicyAgent

policyAgent.reRequest(reqFn, attempts, [name]) ⇒ Promise

Runs a request-promise type function several times if it fails with a 401 status code; creates a new agent session before sending the request again

Kind: instance method of PolicyAgent

Param Type Description
reqFn function Function that returns a Promise
attempts number Number of attempts to retry the function; default: 0 (no retries)
[name] string Name

policyAgent.authenticateAgent() ⇒ Promise

Authenticates the policy agent using the credentials in the config object.

Kind: instance method of PolicyAgent

policyAgent.validateSession(sessionId) ⇒ Promise

Validates a given sessionId against OpenAM and adds a session listener if valid.

Kind: instance method of PolicyAgent

Param Type Description
sessionId string The client's OpenAM session ID

policyAgent.setSessionCookie(res, sessionId)

Sets the session cookie on the response

Kind: instance method of PolicyAgent

Param Type Description
res http~ServerResponse Express Response
sessionId string OpenAM Session ID

policyAgent.getSessionIdFromRequest(req) ⇒ Promise

Gets the session ID from the session cookie in the request

Kind: instance method of PolicyAgent
Returns: Promise - Session ID

Param Type Description
req http~IncomingMessage Express Request

policyAgent.getUserProfile(userId, realm, sessionId) ⇒ Promise

Fetches the user profile for a given username (uid) and saves it to the sessionCache.

Kind: instance method of PolicyAgent

Param Type Description
userId string The user's uid
realm string The user's realm
sessionId string The user's session ID

policyAgent.getPolicyDecision(params) ⇒ Promise

Gets policy decisions from OpenAM for the req.originalUrl resource and the application name specified in the agent config (req must be an instance of IncomingRequest).

Kind: instance method of PolicyAgent

Param Type Description
params object OpenAM policy request params object

policyAgent.registerSessionListener(sessionId) ⇒ Promise

Constructs a RequestSet document containing a AddSessionListener node for sessionId, and sends it to the SessionService.

Kind: instance method of PolicyAgent

Param Type Description
sessionId string The user's session ID

policyAgent.shield(shield) ⇒ function

Initializes the shield and returns an express middleware function that evaluates the shield.

Kind: instance method of PolicyAgent

Param Type Description
shield Shield Shield implementation

Example

var agent = new PolicyAgent(config);
var cookieShield = new CookieShield({getProfiles: true});

// Express
var app = express();
app.use(agent.shield(cookieShield));
app.listen(3000);

// Vanilla Node.js
var server = http.createServer(function (req, res) {
     var middleware = agent.shield(shield);

     if (req.url.match(/some\/path$/) {
         middleware(req, res, function () {
             res.writeHead(200);
             res.write('Hello ' + req.session.data.username);
             res.end();
         });
     }
});
server.listen(3000);

policyAgent.cdsso([path]) ⇒ expess~Router

Expressjs Router factory which handles CDSSO (parses the LARES data and sets the session cookie)

Note that in order for CDSSO to work, you must have the following:

  • An agent profile in OpenAM of type "WebAgent" with all alternative app URLs listed in the "Agent Root URL for CDSSO" (agentRootURL) property
  • The cdsso middleware mounted to the express application
  • A CookieShield mounted to a path with the cdsso option set to true

Kind: instance method of PolicyAgent
Returns: expess~Router - Express middleware

Param Type Default Description
[path] string "/agent/cdsso" The path of the CDSSO endpoint

Example

var openamAgent = require('openam-agent'),
    agent = new openamAgent.PolicyAgent({...}),
    app = require('express')();

app.use(agent.cdsso('/my/cdsso/path'));
app.get('/', new openamAgent.CookieShield(cdsso: true));

policyAgent.getSessionIdFromLARES(lares) ⇒ Promise

Parses the LARES response (CDSSO Assertion) and returns the Session ID if valid

Kind: instance method of PolicyAgent
Returns: Promise - Session ID

Param Type Description
lares string LARES form parameter

policyAgent.getLoginUrl(req) ⇒ string

Returns a regular login URL

Kind: instance method of PolicyAgent

Param Type Description
req http~IncomingMessage Request

policyAgent.getCDSSOUrl(req) ⇒ string

Returns a CDSSO login URL

Kind: instance method of PolicyAgent

Param Type Description
req http~IncomingMessage Request

policyAgent.sessionNotification(notificationSet)

Parses notifications in a notification set and emits a 'session' event for each. CookieShield instances listen on this event to delete any destroyed cookies from the agent's session cache.

Kind: instance method of PolicyAgent
Emits: event:session

Param Type Description
notificationSet object OpenAM notification set (parsed XML document)

policyAgent.notifications([path]) ⇒ express~Router

A express router factory for the notification receiver endpoint. It can be used as a middleware for your express application. It adds a single route: /agent/notifications which can be used to receive notifications from OpenAM. When a notification is received, its contents will be parsed and handled by one of the handler functions.

Kind: instance method of PolicyAgent

Param Type Default Description
[path] string "/agent/notifications" The path of the notification endpoint

Example

var app = require('express')(),
    agent = require('openam-agent').policyAgent(options);

app.use(agent.notifications('/my/notification/path'));