Реализация единого входа для подпапок в домене с использованием Node JS - PullRequest
0 голосов
/ 21 мая 2019

У меня есть требование для реализации единого входа в моем приложении с использованием Node JS. Я новичок в Node JS и SSO. Я просмотрел несколько статей и блогов о SSO и опубликовал их в своем заявлении. Я разместил следующий код на сервере и получил доступ к приложению по URL - https://qa.sp.*****.net. Это перенаправление на новую страницу входа (общая страница входа для всех приложений), если мы предоставим правильные учетные данные, она перейдет на требуемую страницу и покажет мне имя пользователя, как и ожидалось.

app.js

const express = require('express');
const app = express();
const port = 3000;
const https = require('https');
const axios = require('axios');
app.use(express.static(__dirname));
var code = '';
app.get('/', function (req, res) {  
    code = req.query.code;  
    if(code) {      
        axios({
          // make a POST request      
          method: 'post',     
          url: `https://federationdev.XXXXXX.com/as/token.oauth2?code=${req.query.code}&client_id=******&grant_type=authorization_code&scope=profile_email+profile_name+profile_sales+profile_location+profile_org+profile_network+profile_contact&redirect_uri=https://qa.sp.*****.net`,

          // Set the content type header, so that we get the response in JSON     
          headers: {      
            accept: 'application/json'    
          }   
        }).then((response) => {   
          // Once we get the response, extract the access token from the response body   
          const accessToken = response.data.access_token;        
          // res.send("Access Token " +accessToken);
          return res.redirect(`/welcome.html?access_token=${accessToken}`)      
          //return res.redirect(`/sample.pdf`);    // moving to pdf page if it is uncommented
        });
      }
      else
      {     
        return res.redirect(
          `https://federationdev.XXXXXX.com/as/token.oauth2?code=${req.query.code}&client_id=******&grant_type=authorization_code&scope=profile_email+profile_name+profile_sales+profile_location+profile_org+profile_network+profile_contact&redirect_uri=https://qa.sp.*****.net`
        );
      }

}); 
app.listen(0, () => console.log(`Example app listening on port ${port}!`));

Welcome.html

    // We can get the token from the "access_token" query param, available in the browsers "location" global
    const query = window.location.search.substring(1)
    const token = query.split('access_token=')[1]
    // Call the user info API using the fetch browser library
    fetch('https://idp-d.XXXXX.com/upi/profile/', {
            headers: {
                // Include the token in the Authorization header
                Authorization: 'Bearer ' + token
            }
        })
        // Parse the response as JSON
        .then(res => res.json())
        .then(res => {          
            const nameNode = document.createTextNode(`Welcome, ${res.displayName}`)
            document.body.appendChild(nameNode)
        })

Теперь мой запрос: если я хочу открыть PDF-файл по пути ppd/secure/sample1.pdf, используя https://qa.sp.*****.net/ppd/secure/sample1.pdf, он должен быть перенаправлен на страницу входа, как указано выше. Но это не происходит в моем сценарии, а PDF открывается напрямую. Пожалуйста, помогите мне реализовать этот сценарий, так как у меня будет много PDF-файлов в подпапках на сервере, поэтому я хочу перенаправить на страницу входа любые подпапки в домене. Примеры URL https://qa.sp.*****.net/secure/sam.pdf, https://qa.sp.*****.net/ppd/secure/control/abc.pdf

Структура моей папки на сервере.

enter image description here

...