DEV Community

Mitesh Kamat
Mitesh Kamat

Posted on Edited on

Parsing saml namespace prefixes

Introduction

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:root
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
/sh:root

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".

Usage:

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
          }
        });
      }
    })
    res.redirect('http://localhost:3000');
  }
);
Enter fullscreen mode Exit fullscreen mode

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 !!!

Top comments (1)

Collapse
 
jithju31 profile image
Jithju31 •

Hi am not getting any responses in my VS terminal. Please help me on this. How it'll run without mentioning saml request any where in the code?

PS : Am running my project in VS (Visual studio )