Securing Cookie for 3rd Party Identity Management in Drupal maintenance support plans

Securing Cookie for 3rd Party Identity Management in Drupal maintenance support plans

Body
We are in an era where we see a lots of third party integrations being done in projects. In Drupal maintenance support plans based projects, cookie management is done via Drupal maintenance support plans itself to maintain session, whether it be a pure Drupal maintenance support plans project or decoupled Drupal maintenance support plans project,.

But what when we have a scenario where user’s information is being managed by a third party service and no user information is being saved on Drupal maintenance support plans? And when the authentication is done via some other third party services? How can we manage cookie in this case to run our site session and also keep it secure?

One is way is to set and maintain cookie on our own. In this case, our user’s will be anonymous to Drupal maintenance support plans. So, we keep session running based on cookies! The user information will be stored in cookie itself, which then can be validated when a request is made to Drupal maintenance support plans.

We have a php function to set cookie called setCookie() , which we can use to create and destroy cookie. So, the flow will be that a user login request which is made to website is verified via a third party service and then we call setCookie function which sets the cookie containing user information. But, securing the cookie is must, so how do we do that?

For this, let’s refer to Bakery module to see how it does it. It contains functions for encrypting cookie, setting it and validating it.

To achieve this in Drupal maintenance support plans 8, we will write a helper class let’s say “UserCookie.php” and place it in ‘{modulename}/src/Helper/’. Our cookie helper class will contain static methods for setting cookie and validating cookie. Static methods so that we will be able to call them from anywhere.

We will have to encrypt cookie before setting it so we will use openssl_encrypt() php function in following manner:

/**
* Encrypts given cookie data.
*
* @param string $cookieData
* Serialized Cookie data for encryption.
*
* @return string
* Encrypted cookie.
*/
private static function encryptCookie($cookieData) {

// Create a key using a string data.
$key = openssl_digest(Settings::get(‘SOME_COOKIE_KEY’), ‘sha256’);

// Create an initialization vector to be used for encryption.
$iv = openssl_random_pseudo_bytes(16);

// Encrypt cookie data along with initialization vector so that initialization
// vector can be used for decryption of this cookie.
$encryptedCookie = openssl_encrypt($iv . $cookieData, ‘aes-256-cbc’, $key, OPENSSL_RAW_DATA, $iv);

// Add a signature to cookie.
$signature = hash_hmac(‘sha256’, $encryptedCookie, $key);

// Encode signature and cookie.
return base64_encode($signature . $encryptedCookie);
}

String parameter in openssl_digest can be replaced with any string you feel like that can be used as key. You can keep simple keyword too.
Key used should be same while decryption of data.
Same initialization vector will be needed while decrypting the data, so to retrieve it back we append this along with cookie data string.
We also add a signature which is generate used the same key used above. We will verify this key while validating cookie.
Finally, we encode both signature and encrypted cookie data together.
For setting cookie:
 

/**
* Set cookie using user data.
*
* @param string $name
* Name of cookie to store.
* @param mixed $data
* Data to store in cookie.
*/
public static function setCookie($name, $data) {
$data = (is_array($data)) ? json_encode($data) : $data;
$data = self::encrypt($data);
setcookie($name, $cookieData,Settings::get(‘SOME_DEFAULT_COOKIE_EXPIRE_TIME’), ‘/’);
}

Note: You can keep ‘SOME_COOKIE_KEY’ and ‘SOME_DEFAULT_COOKIE_EXPIRE_TIME’ in your settings.php. Settings::get() will fetch that for you.Tip: You can also append and save expiration time of cookie in encrypted data itself so that you can also verify that at time of decryption. This will stop anyone from extending the session by setting cookie timing manually.

Congrats! We have successfully encrypted the user data and set it into a cookie.

Now let’s see how we can decrypt and validate the same cookie.

To decrypt cookie:

/**
* Decrypts the given cookie data.
*
* @param string $cookieData
* Encrypted cookie data.
*
* @return bool|mixed
* False if retrieved signature doesn’t matches
* or data.
*/
public static function decryptCookie($cookieData) {

// Create a key using a string data used while encryption.
$key = openssl_digest(Settings::get(‘SOME_COOKIE_KEY’), ‘sha256’);

// Reverse base64 encryption of $cookieData.
$cookieData = base64_decode($cookieData);

// Extract signature from cookie data.
$signature = substr($cookieData, 0, 64);

// Extract data without signature.
$encryptedData = substr($cookieData, 64);

// Signature should match for verification of data.
if ($signature !== hash_hmac(‘sha256’, $encryptedData, $key)) {
return FALSE;
}

// Extract initialization vector from data appended while encryption.
$iv = substr($string, 64, 16);

// Extract main encrypted string data which contains profile details.
$encrypted = substr($string, 80);

// Decrypt the data using key and
// initialization vector extracted above.
return openssl_decrypt($encrypted, ‘aes-256-cbc’, $key, OPENSSL_RAW_DATA, $iv);
}

We generate the same key using same string parameter given while encryption.
Then we reverse base64 encoding as we need extract signature to verify it.
We generate same signature again as we have used the same key which was used to creating signature while encryption. If doesn’t signatures doesn’t matches, validation fails!
Else, we extract initialization vector from the encrypted data and use to decrypt the data return to be utilized.

/**
* Validates cookie.
*
* @param string $cookie
* Name of cookie.
*
* @return boolean
* True or False based on cookie validation.
*/
public static function validateCookie($cookie) {
if (self::decryptCookie($cookieData)) {
return TRUE;
}
return FALSE;
}

We can verify cookie on requests made to website to maintain our session. You can implement function for expiring cookie for simulating user logout. We can also use decrypted user data out of cookie for serving user related pages.

navneet.singh
Mon, 10/30/2020 – 13:45
Source: New feed

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Securing Cookie for 3rd Party Identity Management in Drupal maintenance support plans

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.