Basic HTTP authentication on a symfony backend

Since I’m not a ninja from this point of view, any better solution is welcome.

You only need to edit your application’s front controller:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php

if ($_SERVER['PHP_AUTH_USER'] !== 'username' || $_SERVER['PHP_AUTH_PW'] !== 'password')
{
  header('WWW-Authenticate: Basic realm="Site Administration Area"');
  header('Status: 401 Unauthorized');
  /* Special Header for CGI mode */
  header('HTTP-Status: 401 Unauthorized');
}
else
{
  require_once(dirname(__FILE__).'/../config/ProjectConfiguration.class.php');

  $configuration = ProjectConfiguration::getApplicationConfiguration('backend', 'prod', false);
  sfContext::createInstance($configuration)->dispatch();
}

The IF block is not something I’ve done by myself ( although it’s really easy ), I’ve taken it from an article on PHPnerds: since the code in the article has a huge flaw don’t use it.

The problem lies in the IF conditions:

1
$_SERVER['PHP_AUTH_USER'] !== 'username' && $_SERVER['PHP_AUTH_PW'] !== 'password'

which are concatenated by an AND and not an OR, leading through a possible unauthorized authentication knowing only the username or the password ( the negative operator ! supports the trick, damn ).

A better solution is to use a more direct approach:

1
2
3
<?php

if ($_SERVER['PHP_AUTH_USER'] == 'username' && $_SERVER['PHP_AUTH_PW'] == 'password')

Hi there! I recently wrote an ebook on web application security, currently sold on leanpub, the Amazon Kindle store and gumroad.

It contains 160+ pages of content dedicated to securing web applications and improving your security awareness when building web apps, with chapters ranging from explaining how to secure HTTP cookies with the right flags to understanding why it is important to consider joining a bug bounty program.

Feel free to skim through some of the free chapters published on this blog and, if the content seems interesting enough to you, grab a copy on leanpub, the Amazon Kindle store, gumroad or simply checkout right down below!

Buy the Web Application Security ebook for $9.99

In the mood for some more reading?

...or check the archives.