Reputation: 283
I want to do a http auth with zend, I read that article http://framework.zend.com/manual/en/zend.auth.adapter.http.html but I dont think its valuable (why the heck are the password taken from an external file...?). I know it can simply be done with headers:
header('WWW-Authenticate: Basic realm=sdfsdf');
header('HTTP/1.0 401 Unauthorized');
die;
but since we are using Zend, I would like to convert it:
$response->setHeader('WWW-Authenticate', 'Basic realm="asda"', true);
$response->setHeader('Status', '401 Unauthorized', true);
it wont accept it, nothing happens. Even if it works, I cant use die();
right after this. Can somebody show a way out?
Upvotes: 3
Views: 2819
Reputation: 6868
Example with a sample action controller:
public function preDispatch() {
if (
!isset($_SERVER['PHP_AUTH_USER'])
|| !isset($_SERVER['PHP_AUTH_PW'])
|| 'admin' != $_SERVER['PHP_AUTH_USER']
|| 'admin' != $_SERVER['PHP_AUTH_PW']
) {
$this->getResponse()->setHeader('WWW-Authenticate', 'Basic realm="Authentication required"');
$this->getResponse()->setHttpResponseCode(401);
if ('not-auth' !== $this->getRequest()->getActionName()) {
$this->_forward('not-auth');
}
}
}
public function indexAction() { }
public function notAuthAction() { }
}
This clever solution was found here. https://gist.github.com/umpirsky/1148691
Upvotes: 0
Reputation: 675
You don't have to use the File resolver. You can write your own resolver class, by simply extending the Zend_Auth_Adapter_Http_Resolver_Interface:
class MyOwnResolver implements Zend_Auth_Adapter_Http_Resolver_Interface
{
/**
* Resolve username/realm to password/hash/etc.
*
* @param string $username Username
* @param string $realm Authentication Realm
* @return string|false User's shared secret, if the user is found in the
* realm, false otherwise.
*/
public function resolve($username, $realm)
{
if ($username == 'testUser' && $realm == 'testPassword') {
return $realm;
} else {
return false;
}
}
}
/* In your controller */
$config = array(
'accept_schemes' => 'basic',
'realm' => 'My Realm',
'nonce_timeout' => 3600,
);
$adapter = new Zend_Auth_Adapter_Http($config);
$result = $adapter->setBasicResolver(new MyOwnResolver())
->setRequest($this->getRequest())
->setResponse($this->getResponse())
->authenticate();
Upvotes: 4