Welcome Guest, Not a member yet? Register   Sign In
CSRF token in post response
#1

[eluser]Unknown[/eluser]
I have a login form and I want to secure it against csrf attacks. Using the suggested pattern in the form helper page, I check the validity of the data (That the user/password combination is correct), then, if it is valid, I redirect the use to the real site. But if the data is not valid, I display a form with an error message. The problem I have is that, when I re-display the form, the csrf token does not appear.

The form:
Code:
<form method="post" accept-charset="utf-8">
  <fieldset>
   <legend><h2>Login</h2></legend>
   &lt;input type="hidden" name="&lt;?=$this-&gt;security-&gt;get_csrf_token_name()?&gt;" value="&lt;?=$this-&gt;security-&gt;get_csrf_hash()?&gt;" />
   <label>Username</label>
   &lt;input type="text" name="username" value="&lt;?= set_value('username') ?&gt;"/&gt;
   <label>Password</label>
   &lt;input type="password" name="password"/&gt;
   &lt;input type="submit" value="Get in"&gt;
  </fieldset>
&lt;/form&gt;

The controller authentication method:
Code:
$request_method = $this->input->server('REQUEST_METHOD');
$this->form_validation->set_rules("username", "Username", "required");
$this->form_validation->set_rules("password", "Password", "required");
if ($request_method == "GET") {
if ($this->session->userdata("username")) redirect("/real_site", "refresh");
$this->load->view("auth.php");
}

if ($request_method == "POST") {
$this->form_validation->run();
$username = $this->input->post("username");
$password = $this->input->post("password");
if (is_valid($username, $password)) {
  /*The validation is with a ldap server, so doesn't matter*/
  redirect("/real_site", "refresh");
}
else {
//This line renders the form again, with an alert, but there is no csrf token
  $this->load->view("auth.php", array("errors" => "wrong user/password."));
}
}

When I return the form in the error case, the form appears, but the hidden field does not have the token. Is there a way to get the token in the post response?

Thanks


[EDIT]Nevermind, it does work, I just forgot a line in the controller[/EDIT]
#2

[eluser]LuckyFella73[/eluser]
Nice you solved your problem - just a hint to make your code clearer:

Userguide:
Quote:If you use the form helper the form_open() function will automatically insert a hidden csrf field in your forms.

Code:
echo form_open('controller_name/method_name');

Then you don't need this one anymore:
Code:
&lt;input type="hidden" name="&lt;?=$this-&gt;security->get_csrf_token_name()?&gt;" value="&lt;?=$this->security->get_csrf_hash()?&gt;" />
#3

[eluser]Unknown[/eluser]
Thanks, I overlook the form_open function when I was reading the Docs.




Theme © iAndrew 2016 - Forum software by © MyBB