Spartan Javascript APIs for NodeJS Applications
This module provides authentication and authorization APIs for client & server applications.
How it works?
- The client application calls
getToken()
API to get a cert token for a the service role. - The
getToken()
fetches token from Spartan Attestation Service for the given role, sign it with client's private key and return back the token to the client application - The client place the cert token in the HTTP request to the service. The app request token is passed as a special HTTP parameter -
x-spartan-auth-token
- Upon receiving request, application server validates the app request token passed on
x-spartan-auth-token
using svcAuth
express route handler. - If the app request token is valid, application checks whether the client application is authorized to access the requested resource and access is granted based on that check.
Getting Started
This section provides a sample NodeJS client and server implementation to demostrate the usage. The client wanted to access a protected service (e.g. /auth-test
). To access this endpoint, the client passes the cert token it received from getToken()
. The service endpoint validates the cert token and grant access to the requested resource.
The following examples are also available in spartan/demo directory
Client
var spartan = require('spartan');
var request = require('request');
var svc_url = 'https://example.com:3001/v1/service/auth-test'
getCertCallback = function(error, certs) {
if (error) {
console.error('Error: failed to return certs from Attestation Service: ' + JSON.stringify(error));
return;
}
var options = {
uri: svc_url,
method: 'POST',
headers: {
'x-spartan-auth-token': certs
},
json: { }
};
request(options, function (error, response, body) {
if (error) {
console.error('Error: service access error:', error);
return;
}
if (response.statusCode != 200) {
console.error(body);
return;
}
var resp = body;
console.log(resp);
});
};
spartan.getToken('SuperRole', { app_privkey: fs.readFileSync('priv.key'),
app_pubkey: fs.readFileSync('pub.key', 'utf8'),
as_pubkey: fs.readFileSync('as-pub.key'),
as_url: 'https://example.com:3000/v1/as/tokens'
}, getCertCallback);
Application Server (NodeJS Express)
var fs = require('fs');
var express = require('express');
var router = express.Router();
var spartan = require('spartan');
var sp_handlr = new spartan.RouteHandler({ as_pubkey: fs.readFileSync(config.asPubKey, 'utf8'),
role: 'SuperRole'
});
router.post('/auth-test', [sp_handlr.svcAuth.bind(sp_handlr)], function(req, res) {
return res.status(200).json({ msg: 'app is authenticated!' });
});
module.exports = router;
API Documentation
The APIs are documented in the source file - index.js
Local packaging:
% npm pack
The above cmd creates a package file.
Install a local package:
% npm install path/to/package/file -save