Redirecting a React page to a SAML login using an Express backend with Passport integration

I have successfully built an application in Express, but I am now transitioning to React, with express serving as an API. My current challenge involves migrating the login page, particularly when it comes to authentication methods:

  • Implementing Passport for user authentication
  • Utilizing SAML (SSO) for seamless authentication
  • For SSO authentication, users are redirected to an external SSO page and then back to the express app.

The login functionality works smoothly in express due to its ability to redirect between pages. However, I'm facing difficulties implementing this feature in React as I can't figure out how to redirect users to the SSO login page (the redirection back is automated by the SSO site).

My current SAML login setup:

router.post('/login',
    passport.authenticate('saml', {
      successRedirect: '/', // Redirect to home page on success
      failureRedirect: 'login', // Redirect to /user/login on failure
    })
);

This is the login form for users:

export class Login extends React.Component{
constructor(props){
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit(){
    fetch("http://localhost:3000/auth/login",
          {method : 'POST'})
          .then(response => alert(response));
}


render(){
    return (
        <div className="flex h-screen">
            <div className="container m-auto max-w-md w-full space-y-8">
                <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
                   Sign in to your account
                 </h2>
                <form className="space-y-6 p-8" onSubmit={this.handleSubmit} id="loginForm">
                    <div>
                       <button type="submit">
                         <span className="absolute left-0 inset-y-0 flex items-center pl-3">
                         Sign in
                       </button>
                     </div>
                </form>
            </div>
        </div>
    );
}

Upon clicking the button, the submit handler initiates a POST request, but I'm unsure of how to proceed with authentication once the request is made.

I attempted to add

action="http://localhost:3000/auth/login" method="post"
to the form. While this successfully redirects to the SSO login page, there are two issues:

  1. The redirect back after SSO login doesn't work since it's a post request (contains user info)
  2. The redirect should be handled by the express server to save cookies, passport data, and complete authentication.
  3. I'm uncertain if this approach would work on a live domain beyond localhost.

Any suggestions or solutions?

Thank you!

Answer №1

To confirm my identity, I set up a public subdomain called auth.domain.com and opened a pop-up window to the authentication page. Once the page was closed, the authentication process should have been successfully completed.

const authLoginURL = 'http://auth.domain.com/login';
const loginWindow = window.open(
                    authLoginURL,
                    "_blank"
            );
const checkInterval = setInterval(() => {
            if(loginWindow.closed) {
                clearInterval(checkInterval);
                this.props.callback();
            }
        }, 1000);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having issues getting Nunjucks templates to render correctly in Express

There seems to be an issue with setting up the template hierarchy in Express or possibly an error in how Nunjucks is being utilized. The goal is to have a template that includes common parts and specific pages that extend this template. It appears that the ...

What is the process to create a sticky Material UI grid element?

Currently, I am in the process of developing the front-end for a shopping cart. To organize the content, I have split the container into two columns using Grid container and Grid item. In each column, various components are placed - the left side containin ...

tips for accessing the useState value once it has been initialized

When using the state hook in my code, I have: const [features, setFeatures] = useState([]) const [medicalProblem, setMedicalProblem] = useState([]) The medicalProblem variable will be initially populated with a response from an API call: useEf ...

Is it possible to nest HTML within a Route component?

<Router> <Routes> <Route path='/' element={<Navbar />} /> <Route path='/' element={<div className='recipes'> {query ? query.map((object, i) => ( <Recipe ...

What is the reason for the find() method not displaying the most recent data from a MongoDB database in an Express.js application?

Upon calling the app.post('/form-submit', funtion(req, res)) method, my expectation is for it to first save the data using save(). This works fine, but then when I call the find() method, it shows all the data from the mongoDB database except for ...

Achieving vertical center alignment in React Native: Tips and techniques

Just a quick heads-up: This question pertains to a school project. I'm currently knee-deep in a full-stack project that utilizes React Native for the front-end. I've hit a bit of a snag when it comes to page layout. Here's the snippet of my ...

The React engine is triggering an error stating "Module not found."

Utilizing react-engine to enable the server with react component access. Through react-engine, you can provide an express react by directing a URL and utilizing res.render. The documentation specifies that you need to supply a path through req.url. app.use ...

Error Alert: UnhandledPromiseRejectionWarning in Async Series Causes Concern

I am currently working on a function in my project that uses the async series method to ensure specific tasks are executed in a certain order. In this case, function1 needs to be completed before function2, which must then be completed before function3. a ...

How to access the onchange text in a react-select search component

I'm currently working on implementing search select functionality in my webpage using the react-select-search npm package. This is my main component: import React, { Component } from "react"; import Task from "./task"; // Rest of ...

Sailsjs middleware that handles parsing of res.body data

I am a newcomer to JavaScript and recently started working with the sails framework. In my middleware, I am attempting to parse the HTTP response body to add a job to the celery queue. Despite following the documentation for skipper-, I continue to encount ...

Managing cookies in an ExpressJS application that runs on the client-side as well

From my perspective, in order for a server side application to track which clients are interacting with it, it needs to store a cookie on the client containing the session ID. This is confirmed by the documentation of express-session, a widely used packag ...

Experiencing difficulty in finding my way to other web pages

I've developed a React website with user authentication and a sidebar. The routes are protected to ensure that only logged-in users can access certain pages. To show the sidebar only after login, I have placed it inside protected routes and kept sign- ...

Attempting to Retrieve Information from a Get Request using Axios

I am attempting to retrieve SQL data from a GET request using axios. My backend is set up with an express server, and the front end is built with React. In my React component, I have a function that contains the axios GET call, which I then invoke within t ...

Switching left navigation in material-ui when the user interacts within the application boundary

I am currently implementing a toggle feature in my AppBar to display the LeftNav. I have successfully set it up to close when the toggle is clicked again. However, I wish to mimic the behavior of most left nav bars where clicking anywhere outside of the ...

Setting up a Node + MongoDB API in the Cloud on either AWS or GCP

Currently, I am developing a Node.js + MongoDB API that is hosted on a virtual machine on Google Cloud Platform. The data for the API is stored in a MongoDB instance running on the same VM. I am wondering if it is advisable to run a local MongoDB instance ...

Operating two socket servers on a single port

I currently have a setup with three servers: Main server - responsible for listening to all HTTP requests Socket Server 1 : Listens to X types of socket requests Socket Server 2 : Listens to Y types of socket requests The goal is to run all three server ...

Command your way through NodeJS with Node Space Dot!

After a hiatus, I returned to my Node JS script in my development directory filled with various test JS scripts. I loaded a script that seemed to be the one I wanted based on its name and most recent date. Using the command: C:\testscripts>node . ...

What is the best way to calculate the total of a field with matching Project and Employee names?

My task involves grouping data from an Array of objects by Project Name and Employee Name, whereby existing projects and employees have their hours added together. projects = [ { "project": { "id": 1, "name": "M ...

Frontend React app encountering communication issue with backend API via proxy connection

Error: Request to /api/v1/products from localhost:3000 could not be proxied to . Refer to https://nodejs.org/api/errors.html#errors_common_system_errors for details (ETIMEDOUT). This issue persists. Frontend -> React Backend -> Express, Node.js ...

Utilizing MUI for layering components vertically: A step-by-step guide

I am looking for a way to style a div differently on Desktop and Mobile devices: ------------------------------------------------------------------ | (icon) | (content) |(button here)| ----------------------------------------- ...