403 Destination

403s or Access Denied pages. We have all been there and experienced them. They can interrupt a perfectly well-designed user experience as well as interrupt a developer’s work.

Recently, we came across a challenge with a login form on a 403 (access denied) page not properly redirecting to the original page after login.

If you’re not familiar with the flow here, if you hit page on a Drupal site that you do not have access to, usually because you’re not logged in, you get a page saying “Access Denied”. Good usability means having a login form right on that page so that if you do have access to the page you can log in and be redirected back to the page you were trying to access instead of having to navigate away to the user login.

Drupal allows you to set any URL as the 403 page, and in this case, there was one defined, but when the 403 page was loaded, there was no destination parameter set.

The destination parameter is used as storage for the ultimate page you want to be redirected to when completing an action such as logging in. This looks like “http://mysite.com/access-denied?destination=my-page“. Once logged in, you would get automatically redirected to “http://mysite.com/my-page“.

In order to fix this, we needed to ensure the destination parameter was being added to the 403 page URL, so we used a hook_drupal_goto_alter implementation to first check if we were getting redirected to the 403 page, then to add the destination parameter to the redirect URL, set to the current page path.

Here’s the code:

/**

* Implements hook_drupal_goto_alter()

* Ensure 403 redirect loads the current path as

* destination parameter

*/

function mymodule_drupal_goto_alter(&$path, &$options, &$http_response_code) {

if($path == variable_get(‘site_403’)) {

$options[‘query’] = array(

‘destination’ => current_path(),

);

}

}

Once you have added this code to your custom module, be sure to clear the site cache so the new function is registered, and don’t forget to test!

__________________________________

Above Code Courtesy of Paul Sheldrake