【问题标题】:How to authenticate users on a React.JS app using j_security_check如何使用 j_security_check 在 React.JS 应用程序上对用户进行身份验证
【发布时间】:2018-12-28 06:43:39
【问题描述】:

我正在开发一个使用 ReactJS 的应用程序。我将在 TomCat 服务器上运行应用程序并使用 Maven 进行部署。对于过去的应用程序,我使用 j_security_check 对用户进行身份验证,并希望以同样的方式在 React 应用程序中对用户进行身份验证。

我的问题在于我不确定如何设置我的 web.xml 文件来限制访问并提示登录。由于 React 只有一个 html 文件和一个 js 文件,我如何限制访问并重定向到不同的组件?我需要有一个单独的 html 页面来登录吗?

如果这是必须以编程方式完成的事情,我将如何设置一个 HttpRequest 来做到这一点,这将是安全的?我尝试了以下代码,但在尝试登录时出现 404 错误。

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");}

【问题讨论】:

    标签: reactjs authentication j-security-check


    【解决方案1】:

    对于遇到此问题的其他人,以下是我们如何使其正确验证。

    在加载网站时,我们会自动加载登录页面。 在 componentDidMount 上,我们调用一个函数,该函数将 XMLHttpRequest 发送到获取位于网站服务器中的文件。文件路径在网站 web.xml 中受到限制,导致它尝试使用 j_security_check 进行身份验证。出于安全考虑,网址已被删除。

    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();
    

    }

    如果用户已经通过身份验证并且有一个活动会话,那么登录页面将被删除,然后将呈现主网站。

    否则用户将使用他们的凭据登录,创建一个活动会话并加载主页。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-16
      • 1970-01-01
      • 2019-08-04
      • 2023-03-11
      • 1970-01-01
      • 2013-06-01
      • 2013-03-09
      • 2019-09-14
      相关资源
      最近更新 更多