0

I can programmatically set a cookie in a Drupal 9 controller and I can see that cookie in Chrome's developer tools. However, I cannot programmatically get that cookie from a hook.

I'm using the SAML Service Provider module. I'm extending the SamlSPDrupalLoginController::initiate() function with this code to set a cookie.

setcookie('stv_saml_idp_id', $idp->get('id'), time() + 86400, '/');

That seems to work fine as I can see the cookie in the Chrome developer tools. Unfortunately, when I attempt to get the cookie back with the following code, I get no results.

function mymodule_saml_sp_drupal_login_user_attributes_alter($user, array $attributes) {
  // …
  $cookies = \Drupal::requestStack()->getCurrentRequest()->cookies;
  $idp_id = $cookies->get('stv_saml_idp_id');
  //…
}

However, if (as a test) I embed the same code in a Basic page, I can get the cookie.

I have also tried with $idp_id = $_COOKIE['stv_saml_idp_id']; but I still could not get the cookie.

How can I read a cookie I programmatically set?

2
  • What are the cookie attributes in fact in the browser?
    – cilefen
    Sep 17 at 4:52
  • Related: is the browser sending that cookie in subsequent requests?
    – cilefen
    Sep 17 at 10:09

1 Answer 1

3

Oh... thanks cilefen. That was a good question that helped me find the problem :-)

I was writing down the attributes to post in reply when I realised my cookie domain differed from the Drupal session cookie domain by 1 character. My cookie domain was:

mysub.domain.com

Whereas, the session cookie had leading dot like so:

.mysub.domain.com

So, the solution was to explicitly set the cookie Domain exactly the same as the Drupal session Domain:

setcookie('stv_saml_idp_id', $idp->get('id'), time() + 86400, '/', '.mysub.domain.com');

Thanks again.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.