Search code examples
reactjsauthenticationj-security-check

How to authenticate users on a React.JS app using j_security_check


I am working on an application that uses ReactJS. I will be running the application on a TomCat server and deploying using Maven. For past applications I have used j_security_check to authenticate users and would like to authenticate users in the React app the same way.

My problem arises in that I am not sure how to set up my web.xml file to restrict access and prompt for a login. Since React only has one html file, and one js file, how do I restrict access and redirect to a different component? Do I need to have a separate html page for my login?

If this is something that has to be done programmatically, how would I go about setting up a HttpRequest to do this that would be secure? I have tried the following code, but am getting a 404 error when I try to login.

handleSub(fields) {
  var xhttp = new XMLHttpRequest();
  xhttp.open("POST", "j_security_check", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("j_username=fields.username&j_password=fields.password");}

Solution

  • For others that are having this issue, below is how we got it to authenticate correctly.

    On loading the website we load up a login page automatically. On componentDidMount, we call a function that sends an XMLHttpRequest to a get a file located in the websites server. The file path is restricted in the websites web.xml causing it to try to authenticate using j_security_check. url's have been removed for security purposes.

    callSecuredFile(){
    var secure = new XMLHttpRequest();
    var url = "/website_name/private/filename.txt";
    secure.onreadystatechange = function(){
      if(secure.readyState === 4 && secure.status ===200){
        try{
          var verificationJSON = JSON.parse(secure.responseText);
          if(verificationJSON.loggedIn === true){
            ReactDOM.render( this.renderSite(document.getElementById('MainPage'));
          }
        }
        catch(e){
          console.log(e);
        }
      }
    }.bind(this);
    secure.open('GET', url, true);
    secure.send();
    

    }

    Should the user already be authenticated and have an active session the login page will be removed and the main website will then be rendered.

    Otherwise the user will login with their credentials, creating an active session and loading the main page.