Parsing saml namespace prefixes

miteshkamat27 profile image Mitesh Kamat ・1 min read


This is about authentication / authorisation while building your web apps.

I included single-sign-on feature in my web application. Then, after integrating my app with SSO, I performed login operation and saw this saml response after authentication.

sh:book /sh:book
sh:genre /sh:genre
sh:id /sh:id
sh:book /sh:book
sh:genre /sh:genre
sh:id /sh:id
sh:book /sh:book
sh:genre /sh:genre
sh:id /sh:id

Apologies.. I don't know how to include html tags in this post :P

How do I handle this? I need a JSON/ object to fetch the concerned values.

I followed these steps to convert it to a json object:
1) Decoded the saml response to xml.
2) Then, parsed xml to object/ JSON to fetch required fields.

For decoding the saml response, I used "saml-encoder-decoder-js" npm package and for parsing xml to object I went for "xml2js".


let decoder = require('saml-encoder-decoder-js'),
parseString = require("xml2js").parseString,
stripPrefix = require("xml2js").processors.stripPrefix;

app.post('/login/callback', function(req, res) {

const xmlResponse = req.body.SAMLResponse;
decoder.decodeSamlPost(xmlResponse, (err,xmlResponse) => {
  if(err) {
    throw new Error(err);
  } else {
    parseString(xmlResponse, { tagNameProcessors: [stripPrefix] }, 
                function(err, result) {
      if (err) {
        throw err;
      } else {
        console.log(result); //End result


Note: stripPrefix to get rid of namespace prefix.
to fetch "root" from "sh:root".

So, the end result gave me the json I was looking for.

Hope, you find this article worthy enough to have a glance.

Cheers !!!


Editor guide