Add cidaas interceptor : node js

npm install cidaas-interceptor-nodejs --save

check your package.json to verify the changes in the dependency section

Usage

The Cidaas Interceptor works as middleware for express.
If you want to use it for Fastify, you have to register it as a hook listening to the 'onRequest' event.

Configuration

import { CidaasInterceptor, CidaasInterceptorConfig } from "cidaas-interceptor-nodejs";

let interceptorConfig = new CidaasInterceptorConfig();

// add your cidaas base url to dicover the urls for you. it will internally discover the url from <cidaas-base-url>/.well-known/openid-configuration
interceptorConfig.baseUrl = "https://<cidaas-base-url>";

// Configure client_id and client_secret , This client must be non-interactive client 
interceptorConfig.client_id = "YOUR CLIENT ID";
interceptorConfig.client_secret = "YOUR CLIENT SECRET";

 // use_local_validation : enables the token validation done in offline , which will improve the performance, LocalTokenCache.removeToken(access_token) need to be called manully when the on the logout webhook
interceptorConfig.use_local_validation = true; 

//Create the cidaas interceptor with the config
cidaas_interceptor = new CidaasInterceptor(interceptorConfig);

//Or update it's config later
cidaas_interceptor.setConfig(interceptorConfig);

Express js

var express = require('express');
var app = express();
var bodyParser = require("body-parser");
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
        extended: true
    })
);

Check Scope

app.get("/serviceurl", cidaas_interceptor.checkAccess({ scopes: ["cidaas:write"] }), function (req, res) {

// your code

});

Check Role

app.post("/serviceurl", cidaas_interceptor.checkAccess({ roles: ["Admin"] }), function (req, res) {

// your code

});

Check Role and Scope

app.get("/serviceurl", cidaas_interceptor.checkAccess({ scopes: ["cidaas:write"], roles: ["Admin"] }), function (req, res) {

// your code

});

DenyAll

app.get("/serviceurl", cidaas_interceptor.checkAccess({denyAll : true}), function (req, res) {

// your code

});

PermitAll

app.get("/serviceurl", cidaas_interceptor.checkAccess({permitAll : true}), function (req, res) {

// your code

});

Or just ignore the inceptor code

app.get("/serviceurl", function (req, res) {

// your code

});

Advanced

Check Role in custom group

app.post("/serviceurl", cidaas_interceptor.checkAccess({ roles: ["Admin"] }), function (req, res) {

// your code

});

Fastify

In Fastify, you have to register the interceptor with the .addHook("onRequest") method as follows:

server.js:

// Require the framework and instantiate it
const fastify = require("fastify")({
  logger: true
});

Create some routes in a seperate file: routes.js

async function routes(fastify, options) {
  fastify
    .addHook(
      "onRequest",
      global.cidaas_interceptor.checkAccess({
        scopes: ["myawesomescope:read"] //If you want to use scopes
      })
    )
    .get("/hello", async (request, reply) => {

        //Your code
      return { hello: "world!" };
    });
}

module.exports = routes;

then simply register the fastify routes in your server.js:

fastify.register(require("./routes"));

If you want other routes in the same server which are not protected or are protected with different scopes, you can achieve this by using fastify context:

otherroutes.js

async function routes(fastify, options) {
  fastify
    .get("/world", async (request, reply) => {
      return { hello: "beautiful world" };
    });
}

module.exports = routes;

Complete server.js example with configuration:

const fastify = require("fastify")({
  logger: true
});

let interceptorConfig = new CidaasInterceptorConfig();

// add your cidaas base url to dicover the urls for you. it will internally discover the url from <cidaas-base-url>/.well-known/openid-configuration
interceptorConfig.baseUrl = "https://<cidaas-base-url>";

// Configure client_id and client_secret , This client must be non-interactive client 
interceptorConfig.client_id = "YOUR CLIENT ID";
interceptorConfig.client_secret = "YOUR CLIENT SECRET";

 // use_local_validation : enables the token validation done in offline , which will improve the performance, LocalTokenCache.removeToken(access_token) need to be called manully when the on the logout webhook
interceptorConfig.use_local_validation = true; 

//Create the cidaas interceptor with the config
global.cidaas_interceptor = new CidaasInterceptor(interceptorConfig);

//Or update it's config later
global.cidaas_interceptor.setConfig(interceptorConfig);

//register another routes-file
fastify.register(require("./routes"));
fastify.register(require("./otherRoutes"));

// Declare a route
fastify.get("/", function(request: any, reply: any) {
  reply.status(300).send({ hello: "world" });
});

// Run the server!
fastify.listen(3000, function(err: any, address: any) {
  if (err) {
    fastify.log.error(err);
    process.exit(1);
  }
  fastify.log.info(`server listening on ${address}`);
});

The usage of the parameters for the intercepor are exactly the same as with the express examples

Note:

The cidaas_interceptor.expressMiddleware method is deprecated since version 2.4.0, please use the checkAccess-method instead.

Context variables (Magic variables)

Once the validation passed , cidaas will automatically add the __userid and __access_token in the Current header.

console.log(req.headers.__userId);
console.log(req.headers.__access_token);

It contains the userid of the access_token and the passed access_token

Note
Node vs Java interceptor comparison

1. Unlike the Java interceptor, you have to add the cidaas interceptor to all route methods which need to be secured. If the method does not have the cidaas interceptor, that is equal to java's @PermitAll

2. Java's @OAuthScopes(scopes = { "cidaas:write", ... }) == global.cidaas_interceptor({ scopes: ["cidaas:write", ...]})

3. Java's @RolesAllowed(value = { "role1", "role2", ... }) == global.cidaas_interceptor({ roles: ["role1", "role2", ...]})

4. Don't have support for JWE.


results matching ""

    No results matching ""