Skip to content
joshchan edited this page Aug 23, 2012 · 4 revisions

CAS Client for Node.js

CAS (Central Authentication Service) is a single sign-on service. It allows users to log in once to a central server and be recognized by many separate websites and services. This project is a Node.js implementation of the CAS client, supporting protocol versions 1.0, 2.0, and maybe a bit of 3.0.

Dependencies

This uses the jsdom module for parsing XML responses from the CAS server.

Installation

npm install jsdom
git clone git@github.com:joshchan/node-cas.git node_modules/cas

Bare essentials

Let's say a user is on your site and has not yet authenticated.

First initialize the CAS client object:

    var CAS = require('cas');
    var cas = new CAS({
        base_url: 'https://my-cas-server.example.com/cas',
        service: 'http://my-web-server.example.com/my/service',
        version: 1.0
    });

Then check to see if the ticket parameter is present in the query string. If so, that means the user has just been redirected from the CAS server after successfully authenticating there. We can proceed to authenticate the user by validating the ticket.

If there is no ticket present, then we immediately redirect to the CAS server. The user will authenticate there and be sent back with a ticket.

An example, with the Express framework:

    var cas_login = function(req, res) {
      var ticket = req.param('ticket');
      if (ticket) {
        cas.validate(ticket, function(err, status, username) {
          if (err) {
            // Handle the error
            // ...
            res.send({error: err});
          } else {
            // Log the user in
            // ...
            res.send({status: status, username: username});
          }
        });
      } else {
        // Send user to the CAS server
        res.redirect('https://my-cas-server.example.com/cas/login?service=' + urlencode(cas.service));
      }
    };

Automatic redirection

Use the authenticate() method. This automatically checks for the ticket parameter and redirects the user to the CAS server if needed.

    var CAS = require('cas');
    var cas = new CAS({
        base_url: 'https://my-cas-server.example.com/cas',
        version: 2.0
    });

    var cas_login = function(req, res) {
        cas.authenticate(req, res, function(err, status, username, extended) {
            if (err) {
                // handle the error
                // ...
            } else {
                // log the user in
                // ...
                console.log('User ' + username + ' logged in through CAS');
            }
        }
    }

Logging out

    cas.logout(req, res, 'http://my-website.example.com/home', true);

More