I currently have these 2 functions, one for generating token and one for checking the validity:
function getToken() {
if(isset($_SESSION['token'])) {
return $_SESSION['token'];
} else {
$token = //random key generator goes here;
$_SESSION['token'] = $token;
return $token;
}
}
function validateToken($token) {
if ($token == getToken()){
return true;
} else {
return false;
}
}
And my registration form includes this hidden input:
<input type="hidden" name="token" value="<?php echo getToken(); ?>">
Is this safe? I'm asking because what if session of legit user expires and then they get CSRF'd to this register form and token gets generated by the malicious site/iframe itself because one didn't already exist in the session, therefore authenticating just fine?
Assume that user stays logged in because of cookies.
Am I understanding things wrongly here? Can't remote linking like iframes generate sessions in your backend?
No. As far as I can tell, you are doing it right way as the token should be generated as soon as the user comes to the form page. Then you will generate it to know for sure that someone (real user) actually has visited your form and then you are setting the token for them.
When they do any action with the form, you are checking with the token to see if the token is valid for that user. So, I guess you are doing it right.
One thing, generate the token and store it on session when an user requests/comes to the form page. It would be better if you generate it every time a request comes. Then after each successful form submission, clear the checked token from session.