Insights Hub Obtaining Current Logged-In User in Insights Hub

2024-05-08T11:24:21.000-0400
APIs & Services Applications

Summary

When developing an app within Insights Hub, you may need to know about the currently logged-in user. This article provides methods to achieve this, by inspecting the JWT token in the request headers.


Details

To obtain the currently logged-in user in Insights Hub, follow these steps:

Inspect JWT Token in Request Headers:
   - Check the token at the request of your application that delivers your front end. The JWT token is typically found in the Authorization header.
   - Once you decode the JWT token, you can extract user information, such as the user's email.

Or

Create a Custom Endpoint:
   - Define a small endpoint in your application (e.g., /services/me) that accepts the JWT token.
   - Extract the user email from the JWT token.
   - Query the User Management API using the extracted email to retrieve detailed user information.

Deploy Node.js Code in Cloud Foundry:
   - Deploy the following Node.js code in Cloud Foundry of Insights Hub to obtain the Authorization header:

Package.json:

{
  "name": "api_app_testing",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "nodemon app.js",
  },
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "jsonwebtoken": "^9.0.2",
    "jwks-rsa": "^3.1.0"
  }
}

 

app.js:

const express = require("express");
const app = express();
const axios = require("axios");
const cors = require("cors");
const jwt = require("jsonwebtoken");
const jwksrsa = require("jwks-rsa");
const { log } = require("debug/src/node");

app.use(cors());

//var port = 6002;
var port = process.env.PORT || 6002;
//app.set('port', process.env.PORT || 8080);
app.listen(port, function () {
  console.log("Server is running on port:", port);
});

if (process.env.VCAP_APPLICATION) {
  if (!process.env.MDSP_TENANT)
    throw new Error("missing MDSP_TENANT configuration");
  if (!process.env.MDSP_REGION)
    throw new Error("missing MDSP_REGION configuration");

  console.log(`Configured Insights Hub/MindSphere Tenant: ${process.env.MDSP_TENANT}`);
  console.log(`Configured Insights Hub/MindSphere Region: ${process.env.MDSP_REGION}`);
}

const NON_MDSP_USER = {
  id: "0000-0000",
  name: "John Doe",
  email: "john.doe@example.com",
};

const jwksClient = jwksrsa({
  cache: true,
  rateLimit: true,
  jwksRequestsPerMinute: 5,
  jwksUri: `https://${process.env.MDSP_TENANT}.piam.${process.env.MDSP_REGION}.mindsphere.io/token_keys`,
});
const getKey = (header, callback) => {
  jwksClient.getSigningKey(header.kid, (err, key) => {
    const signingKey = key.publicKey || key.rsaPublicKey;
    callback(null, signingKey);
  });
};
const options = {
  issuer: `https://${process.env.MDSP_TENANT}.piam.${process.env.MDSP_REGION}.mindsphere.io/oauth/token`,
  algorithms: ["RS256"],
};

// On API requests, expect a user identifier:
// - local: use static identifier (same for all)
// - mdsp: extract & use mdsp user identifier from jwt
app.use("/v2/", (req, res, next) => {
  if (process.env.VCAP_APPLICATION) {
    if (req.headers.authorization) {
      console.log("token:", req.headers.authorization);
      let splitAuthHeader = req.headers.authorization.split(" ");
      if (splitAuthHeader[0].toLowerCase() === "bearer") {
        new Promise((resolve, reject) => {
          jwt.verify(
            splitAuthHeader[1],
            getKey,
            { algorithms: ["RS256"] },
            (err, token) => {
              if (err || !token) {
                reject(err);
              }
              resolve(token);
            }
          );
        })
          .then((token) => {
            if (token.user_id) {
              res.locals.todo_user = {
                id: token.user_id,
                name: token.user_name,
                email: token.email,
              };
              next();
            } else {
              next("cannot find user id in token");
            }
          })
          .catch((err) => {
            next(err);
          });
      }
    }
  } else {
    res.locals.todo_user = NON_MDSP_USER;
    next();
  }
});

const getCurrentUser = (res) => {
  if (!res.locals.todo_user) {
    console.error("unknown user, no data available or unauthenticated");
  }
  return res.locals.todo_user;
};

app.get("/", function (req, res) {
  let objData = {
    message: "API app is running fine!",
  };

  res.send(objData);
});

 

Set Environment Variables:
   - Add two environment variables in your app environment:
     - MDSP_TENANT: Your Insights Hub tenant name
     - MDSP_REGION: Your Insights Hub region (e.g., eu1)

   Use the following commands to set environment variables:

cf set-env APP_NAME MDSP_TENANT YOUR_TENANT_NAME
cf set-env APP_NAME MDSP_REGION eu1

Replace `APP_NAME` with your application name in Cloud Foundry, and `YOUR_TENANT_NAME` with your Insights Hub tenant name.

By following these steps, you can effectively retrieve information about the currently logged-in user within Insights Hub.

KB Article ID# KB000132214_EN_US

Contents

SummaryDetails

Associated Components

APIs & Services - Other