DigestAuthenticate
extends BasicAuthenticate
in package
Digest Authentication adapter for AuthComponent.
Provides Digest HTTP authentication support for AuthComponent.
Using Digest auth
Load AuthComponent
in your controller's initialize()
and add 'Digest' in 'authenticate' key
$this->loadComponent('Auth', [
'authenticate' => ['Digest'],
'storage' => 'Memory',
'unauthorizedRedirect' => false,
]);
You should set storage
to Memory
to prevent CakePHP from sending a
session cookie to the client.
You should set unauthorizedRedirect
to false
. This causes AuthComponent
to
throw a ForbiddenException
exception instead of redirecting to another page.
Since HTTP Digest Authentication is stateless you don't need call setUser()
in your controller. The user credentials will be checked on each request. If
valid credentials are not provided, required authentication headers will be sent
by this authentication provider which triggers the login dialog in the browser/client.
Generating passwords compatible with Digest authentication.
DigestAuthenticate requires a special password hash that conforms to RFC2617.
You can generate this password using DigestAuthenticate::password()
$digestPass = DigestAuthenticate::password($username, $password, env('SERVER_NAME'));
If you wish to use digest authentication alongside other authentication methods,
it's recommended that you store the digest authentication separately. For
example User.digest_pass
could be used for a digest password, while
User.password
would store the password hash for use with other methods like
Basic or Form.
Tags
Table of Contents
Properties
- $_config : array<string, mixed>
- Runtime config
- $_configInitialized : bool
- Whether the config property has already been configured with defaults
- $_defaultConfig : array<string, mixed>
- Default config for this object.
- $_needsPasswordRehash : bool
- Whether the user authenticated by this class requires their password to be rehashed with another algorithm.
- $_passwordHasher : AbstractPasswordHasher|null
- Password hasher instance.
- $_registry : ComponentRegistry
- A Component registry, used to get more components.
- $_tableLocator : LocatorInterface|null
- Table locator instance
- $defaultTable : string|null
- This object's default table alias.
Methods
- __construct() : mixed
- Constructor
- authenticate() : array<string, mixed>|false
- Authenticate a user using HTTP auth. Will use the configured User model and attempt a login using HTTP auth.
- configShallow() : $this
- Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
- fetchTable() : Table
- Convenience method to get a table instance.
- generateResponseHash() : string
- Generate the response hash for a given digest array.
- getConfig() : mixed
- Returns the config.
- getConfigOrFail() : mixed
- Returns the config for this specific key.
- getTableLocator() : LocatorInterface
- Gets the table locator.
- getUser() : array<string, mixed>|false
- Get a user based on information in the request. Used by cookie-less auth for stateless clients.
- implementedEvents() : array<string, mixed>
- Returns a list of all events that this authenticate class will listen to.
- loginHeaders() : array<string, string>
- Generate the login headers
- needsPasswordRehash() : bool
- Returns whether the password stored in the repository for the logged in user requires to be rehashed with another algorithm
- parseAuthData() : array<string|int, mixed>|null
- Parse the digest authentication headers and split them up.
- password() : string
- Creates an auth digest password hash to store
- passwordHasher() : AbstractPasswordHasher
- Return password hasher object
- setConfig() : $this
- Sets the config.
- setTableLocator() : $this
- Sets the table locator.
- unauthenticated() : Response|null|void
- Handles an unauthenticated access attempt by sending appropriate login headers
- _configDelete() : void
- Deletes a single config key.
- _configRead() : mixed
- Reads a config key.
- _configWrite() : void
- Writes a config key.
- _findUser() : array<string, mixed>|false
- Find a user record using the username and password provided.
- _getDigest() : array<string, mixed>|null
- Gets the digest headers from the request/environment.
- _query() : Query
- Get query object for fetching user from database.
- generateNonce() : string
- Generate a nonce value that is validated in future requests.
- validNonce() : bool
- Check the nonce to ensure it is valid and not expired.
Properties
$_config
Runtime config
protected
array<string, mixed>
$_config
= []
$_configInitialized
Whether the config property has already been configured with defaults
protected
bool
$_configInitialized
= false
$_defaultConfig
Default config for this object.
protected
array<string, mixed>
$_defaultConfig
= ['fields' => ['username' => 'username', 'password' => 'password'], 'userModel' => 'Users', 'finder' => 'all', 'passwordHasher' => 'Default']
-
fields
The fields to use to identify a user by. -
userModel
The alias for users table, defaults to Users. -
finder
The finder method to use to fetch user record. Defaults to 'all'. You can set finder name as string or an array where key is finder name and value is an array passed toTable::find()
options. E.g. ['finderName' => ['some_finder_option' => 'some_value']] -
passwordHasher
Password hasher class. Can be a string specifying class name or an array containingclassName
key, any other keys will be passed as config to the class. Defaults to 'Default'.
$_needsPasswordRehash
Whether the user authenticated by this class requires their password to be rehashed with another algorithm.
protected
bool
$_needsPasswordRehash
= false
$_passwordHasher
Password hasher instance.
protected
AbstractPasswordHasher|null
$_passwordHasher
$_registry
A Component registry, used to get more components.
protected
ComponentRegistry
$_registry
$_tableLocator
Table locator instance
protected
LocatorInterface|null
$_tableLocator
$defaultTable
This object's default table alias.
protected
string|null
$defaultTable
= null
Methods
__construct()
Constructor
public
__construct(ComponentRegistry $registry[, array<string, mixed> $config = [] ]) : mixed
Besides the keys specified in BaseAuthenticate::$_defaultConfig, DigestAuthenticate uses the following extra keys:
-
secret
The secret to use for nonce validation. Defaults to Security::getSalt(). -
realm
The realm authentication is for, Defaults to the servername. -
qop
Defaults to 'auth', no other values are supported at this time. -
opaque
A string that must be returned unchanged by clients. Defaults tomd5($config['realm'])
-
nonceLifetime
The number of seconds that nonces are valid for. Defaults to 300.
Parameters
- $registry : ComponentRegistry
-
The Component registry used on this request.
- $config : array<string, mixed> = []
-
Array of config to use.
authenticate()
Authenticate a user using HTTP auth. Will use the configured User model and attempt a login using HTTP auth.
public
authenticate(ServerRequest $request, Response $response) : array<string, mixed>|false
Parameters
- $request : ServerRequest
-
The request to authenticate with.
- $response : Response
-
The response to add headers to.
Return values
array<string, mixed>|false —Either false on failure, or an array of user data on success.
configShallow()
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
public
configShallow(array<string, mixed>|string $key[, mixed|null $value = null ]) : $this
Setting a specific value:
$this->configShallow('key', $value);
Setting a nested value:
$this->configShallow('some.nested.key', $value);
Updating multiple config settings at the same time:
$this->configShallow(['one' => 'value', 'another' => 'value']);
Parameters
- $key : array<string, mixed>|string
-
The key to set, or a complete array of configs.
- $value : mixed|null = null
-
The value to set.
Return values
$thisfetchTable()
Convenience method to get a table instance.
public
fetchTable([string|null $alias = null ][, array<string, mixed> $options = [] ]) : Table
Parameters
- $alias : string|null = null
-
The alias name you want to get. Should be in CamelCase format. If
null
then the value of $defaultTable property is used. - $options : array<string, mixed> = []
-
The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
Tags
Return values
TablegenerateResponseHash()
Generate the response hash for a given digest array.
public
generateResponseHash(array<string, mixed> $digest, string $password, string $method) : string
Parameters
- $digest : array<string, mixed>
-
Digest information containing data from DigestAuthenticate::parseAuthData().
- $password : string
-
The digest hash password generated with DigestAuthenticate::password()
- $method : string
-
Request method
Return values
string —Response hash
getConfig()
Returns the config.
public
getConfig([string|null $key = null ][, mixed $default = null ]) : mixed
Usage
Reading the whole config:
$this->getConfig();
Reading a specific value:
$this->getConfig('key');
Reading a nested value:
$this->getConfig('some.nested.key');
Reading with default value:
$this->getConfig('some-key', 'default-value');
Parameters
- $key : string|null = null
-
The key to get or null for the whole config.
- $default : mixed = null
-
The return value when the key does not exist.
Return values
mixed —Configuration data at the named key or null if the key does not exist.
getConfigOrFail()
Returns the config for this specific key.
public
getConfigOrFail(string $key) : mixed
The config value for this key must exist, it can never be null.
Parameters
- $key : string
-
The key to get.
Tags
Return values
mixed —Configuration data at the named key
getTableLocator()
Gets the table locator.
public
getTableLocator() : LocatorInterface
Return values
LocatorInterfacegetUser()
Get a user based on information in the request. Used by cookie-less auth for stateless clients.
public
getUser(ServerRequest $request) : array<string, mixed>|false
Parameters
- $request : ServerRequest
-
Request object.
Return values
array<string, mixed>|false —Either false or an array of user information
implementedEvents()
Returns a list of all events that this authenticate class will listen to.
public
implementedEvents() : array<string, mixed>
An authenticate class can listen to following events fired by AuthComponent:
-
Auth.afterIdentify
- Fired after a user has been identified using one of configured authenticate class. The callback function should have signature likeafterIdentify(EventInterface $event, array $user)
when$user
is the identified user record. -
Auth.logout
- Fired when AuthComponent::logout() is called. The callback function should have signature likelogout(EventInterface $event, array $user)
where$user
is the user about to be logged out.
Return values
array<string, mixed> —List of events this class listens to. Defaults to []
.
loginHeaders()
Generate the login headers
public
loginHeaders(ServerRequest $request) : array<string, string>
Parameters
- $request : ServerRequest
-
Request object.
Return values
array<string, string> —Headers for logging in.
needsPasswordRehash()
Returns whether the password stored in the repository for the logged in user requires to be rehashed with another algorithm
public
needsPasswordRehash() : bool
Return values
boolparseAuthData()
Parse the digest authentication headers and split them up.
public
parseAuthData(string $digest) : array<string|int, mixed>|null
Parameters
- $digest : string
-
The raw digest authentication headers.
Return values
array<string|int, mixed>|null —An array of digest authentication headers
password()
Creates an auth digest password hash to store
public
static password(string $username, string $password, string $realm) : string
Parameters
- $username : string
-
The username to use in the digest hash.
- $password : string
-
The unhashed password to make a digest hash for.
- $realm : string
-
The realm the password is for.
Return values
string —the hashed password that can later be used with Digest authentication.
passwordHasher()
Return password hasher object
public
passwordHasher() : AbstractPasswordHasher
Tags
Return values
AbstractPasswordHasher —Password hasher instance
setConfig()
Sets the config.
public
setConfig(array<string, mixed>|string $key[, mixed|null $value = null ][, bool $merge = true ]) : $this
Usage
Setting a specific value:
$this->setConfig('key', $value);
Setting a nested value:
$this->setConfig('some.nested.key', $value);
Updating multiple config settings at the same time:
$this->setConfig(['one' => 'value', 'another' => 'value']);
Parameters
- $key : array<string, mixed>|string
-
The key to set, or a complete array of configs.
- $value : mixed|null = null
-
The value to set.
- $merge : bool = true
-
Whether to recursively merge or overwrite existing config, defaults to true.
Tags
Return values
$thissetTableLocator()
Sets the table locator.
public
setTableLocator(LocatorInterface $tableLocator) : $this
Parameters
- $tableLocator : LocatorInterface
-
LocatorInterface instance.
Return values
$thisunauthenticated()
Handles an unauthenticated access attempt by sending appropriate login headers
public
unauthenticated(ServerRequest $request, Response $response) : Response|null|void
Parameters
- $request : ServerRequest
-
A request object.
- $response : Response
-
A response object.
Tags
Return values
Response|null|void_configDelete()
Deletes a single config key.
protected
_configDelete(string $key) : void
Parameters
- $key : string
-
Key to delete.
Tags
_configRead()
Reads a config key.
protected
_configRead(string|null $key) : mixed
Parameters
- $key : string|null
-
Key to read.
_configWrite()
Writes a config key.
protected
_configWrite(array<string, mixed>|string $key, mixed $value[, string|bool $merge = false ]) : void
Parameters
- $key : array<string, mixed>|string
-
Key to write to.
- $value : mixed
-
Value to write.
- $merge : string|bool = false
-
True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
Tags
_findUser()
Find a user record using the username and password provided.
protected
_findUser(string $username[, string|null $password = null ]) : array<string, mixed>|false
Input passwords will be hashed even when a user doesn't exist. This helps mitigate timing attacks that are attempting to find valid usernames.
Parameters
- $username : string
-
The username/identifier.
- $password : string|null = null
-
The password, if not provided password checking is skipped and result of find is returned.
Return values
array<string, mixed>|false —Either false on failure, or an array of user data.
_getDigest()
Gets the digest headers from the request/environment.
protected
_getDigest(ServerRequest $request) : array<string, mixed>|null
Parameters
- $request : ServerRequest
-
Request object.
Return values
array<string, mixed>|null —Array of digest information.
_query()
Get query object for fetching user from database.
protected
_query(string $username) : Query
Parameters
- $username : string
-
The username/identifier.
Return values
QuerygenerateNonce()
Generate a nonce value that is validated in future requests.
protected
generateNonce() : string
Return values
stringvalidNonce()
Check the nonce to ensure it is valid and not expired.
protected
validNonce(string $nonce) : bool
Parameters
- $nonce : string
-
The nonce value to check.