简体   繁体   中英

React/CSRF: Passing Back CSRF tokens without using forms and hidden input values

React: ^0.14.X

Sanity Check - It's common in React to build custom input components that use ajax and since tokens are passed to clients as a part of state I can imagine with React the need to use forms and hidden input values to pass csrf tokens is a step that can be skipped altogether , but when EVERYBODY on Github still building React apps that use forms and hidden input values- you start think there has to be some magicial reason why.

Now I know forms and hidden input values is how it is suggested to be handled in Node/SPA applications...

... but with React I don't see a reason for the CSRF token to ever touch the DOM(where I guess it would be susceptible to being stole), but rather just accessed from the component's state and pass it along whenever a submission is made.

For example this Login Component that passes the csrf out from component state(to be handled later by ajax).

var Login = React.createClass({

  getInitialState: function() {
    return{
      csrf: this.props.csrf,
      email:'',
      password: ''
    }
  },

  onEmailChange: function(event) {
    this.setState({email: event.target.value});
  },

  onPasswordChange: function(event) {
    this.setState({password: event.target.value});
  },

  onSubmit: function() {
    ActionCreators.login(this.state.email, this.state.password,this.state.csrf); 
  },

  render: function(){

    return (

        <div className="login-block">
            <input type="text" placeholder="Email" id="input" onChange={this.onEmailChange}/>
            <input type="password" placeholder="Password" id="input" onChange={this.onPasswordChange}/>
            <button onClick={this.onSubmit}>Submit</button>
        </div>

    )
  }

});

Question: Is there some sort of vuneribility that the code above would cause in my application that I should consider using a form and a hidden input value?

I don't think so, I think its just a hold-over from pre-SPA days. Maybe actually with an SPA you would ideally want to get new CSRF tokens somehow after every state change, like an AJAX request or websocket request, which wouldn't be possible if you were using a form that wasn't being refreshed. In our app actually the CSRF token is sent via some var csrftokenblah = that is written by the EJS template rendering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM