XF 2.0 CSRF Token Question

i_n_k

Member
I'm trying to understand the use behind the CSRF token, which I understand is for security. I'm working on a custom script and I'm trying to understand its use and how to validate it.

From what I can see, I've had no issue obtaining it via this bit of code:

Code:
$token = \XF::app()['csrf.token'];

So I'm pulling it and then passing it via a form in a hidden format, but It seems like it updates with every page refresh, and I can't get it to match when I pass it because the value has already changed to a new one. Is that not the spirit it was intended for, or am I missing something? I appreciate any guidance anyone might be able to provide. Everything else has been pretty straightforward but I'm trying to tighten up a few things and I'd like to finally master this one, so thank you in advance to anyone who can help me figure this one out.
 
Last edited:
Just to follow up on this - how is this used? As I mentioned, I noticed it changes on page refresh so I'm just trying to understand the idea behind using this in an add-on, etc for securing the session. Both @Mike and @Brogan have been helpful in the past, perhaps you guys might provide some insight?
 
From the theoretical part, a CSRF token is like an OTP or a PIN. It serves as an additional authentication layer for just as long as the token is active. It's purpose is to secure you against CSRF attacks, which, in very simple terms, are actions triggered via links. That's why the token get's refreshed on every page call (or at least on every relevant action).
From the practical part, you would want to pass in the CSRF token in your template. Why in your template? Because this token won't refresh until after the form is submitted, so you can use it during the form processing. You can add the token to your form like this:
HTML:
<input type="hidden" name="_xfToken" value="{$visitor.csrf_token_page}" />
In your controller, you then would call $this->assertValidCsrfToken();. I believe this is done by default for post requests, but not sure on that one.
 
Top Bottom