DEV Community

Mitesh Kamat
Mitesh Kamat

Posted on • Edited on

2

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

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 )

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more