1

To prevent CSRF attacks, I'm adding a state parameter with my current CSRF token to an external link. When the external page redirects the user back to my site, it will include the state.

With a simple condition I can check it in my controller:

if($data['state'] !== csrf_token()){
    throw new TokenMismatchException;
}

Now I want to write a test for it to pass the if condition, but csrf_token() is empty in the test directory, however not in the controller. So it fails, unfortunately. Here is an excerpt of the test:

/** @test */
public function it_saves_the_data_in_database() 
{
  $this->get(route('connect.index', [
    'scope' => $this->scope,
    'code' => $this->code,
    'state' => csrf_token(), //it's null here...
  ]))->assertStatus(200); //however it returns 419
}

Is it possible to generate the token before?

5
  • My current solution is ugly: if($data['state'] !== csrf_token() && (env('APP_ENV') === "testing" && $data['state'] !== 'testing')) Commented Aug 22, 2018 at 12:33
  • Why do you need to check the token in your controller? Use the included middleware.. Commented Aug 22, 2018 at 12:36
  • @Devon, as I understand, it won't work. The redirect URI is a get route and the parameter is set to "state" with the token. Commented Aug 22, 2018 at 12:38
  • Ok, I see, but not sure why'd you need a csrf token for a get request. sounds like an XY problem then. Commented Aug 22, 2018 at 12:42
  • @Devon sorry needed to be afk, but I need this for Stripe Connect. See here: stripe.com/docs/connect/standard-accounts Commented Aug 22, 2018 at 12:55

1 Answer 1

2

If you wrote HTTP access testing code before you use crsf_token() like below example.

The csrf token seems to be generated in that test session.

$this->get(...)

$this->get(route('connect.index', [
    'scope' => $this->scope,
    'code' => $this->code,
    'state' => csrf_token(), //it's null here...
  ]))->assertStatus(200);
Sign up to request clarification or add additional context in comments.

1 Comment

hello, how did you fix this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.