Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 21 additions & 22 deletions docs/en/authenticators.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ public function getAuthenticationService(ServerRequestInterface $request): Authe
// ...
$service->loadAuthenticator('Authentication.Jwt', [
'identifier' => 'Authentication.JwtSubject',
'secretKey' => file_get_contents(CONFIG . '/jwt.key'),
'secretKey' => file_get_contents(CONFIG . 'jwt.key'),
'algorithm' => 'RS256',
'returnPayload' => false
]);
Expand All @@ -196,11 +196,11 @@ In your `UsersController`:
``` php
use Firebase\JWT\JWT;

public function login()
public function login(): void
{
$result = $this->Authentication->getResult();
if ($result->isValid()) {
$privateKey = file_get_contents(CONFIG . '/jwt.key');
$privateKey = file_get_contents(CONFIG . 'jwt.key');
$user = $result->getData();
$payload = [
'iss' => 'myapp',
Expand Down Expand Up @@ -260,16 +260,19 @@ distribute it via a JWKS endpoint by configuring your app as follows:
``` php
// config/routes.php
$builder->setExtensions('json');
$builder->connect('/.well-known/:controller/*', [
$builder->connect('/.well-known/{controller}', [
'action' => 'index',
], [
'controller' => '(jwks)',
'controller' => 'jwks',
'pass' => [],
]); // connect /.well-known/jwks.json to JwksController

// controller/JwksController.php
use Firebase\JWT\JWT;

public function index()
{
$pubKey = file_get_contents(CONFIG . './jwt.pem');
$pubKey = file_get_contents(CONFIG . 'jwt.pem');
$res = openssl_pkey_get_public($pubKey);
$detail = openssl_pkey_get_details($res);
$key = [
Expand Down Expand Up @@ -313,7 +316,7 @@ Configuration options:

- **realm**: Default is `null`
- **qop**: Default is `auth`
- **nonce**: Default is `uniqid(''),`
- **nonce**: Default is `uniqid('')`
- **opaque**: Default is `null`

## Cookie Authenticator aka "Remember Me"
Expand Down Expand Up @@ -344,7 +347,7 @@ Configuration options:
- **samesite**: String/null The value for the same site attribute.

The defaults for the various options besides `cookie.name` will be those
set for the `Cake\Http\Cookie\Cookie` class. See [Cookie::setDefaults()](https://api.cakephp.org/4.0/class-Cake.Http.Cookie.Cookie.html#setDefaults)
set for the `Cake\Http\Cookie\Cookie` class. See [Cookie::setDefaults()](https://api.cakephp.org/5/class-Cake.Http.Cookie.Cookie.html#setDefaults)
for the default values.

- **fields**: Array that maps `username` and `password` to the
Expand All @@ -369,16 +372,16 @@ Configuration options:
The cookie authenticator can be added to a Form & Session based
authentication system. Cookie authentication will automatically re-login users
after their session expires for as long as the cookie is valid. If a user is
explicity logged out via `AuthenticationComponent::logout()` the
explicitly logged out via `AuthenticationComponent::logout()` the
authentication cookie is **also destroyed**. An example configuration would be:

``` php
// In Application::getAuthenticationService()

// Reuse fields in multiple authenticators.
$fields = [
AbstractIdentifier::CREDENTIAL_USERNAME => 'email',
AbstractIdentifier::CREDENTIAL_PASSWORD => 'password',
PasswordIdentifier::CREDENTIAL_USERNAME => 'email',
PasswordIdentifier::CREDENTIAL_PASSWORD => 'password',
];

// Put form authentication first so that users can re-login via
Expand All @@ -389,9 +392,7 @@ $service->loadAuthenticator('Authentication.Form', [
'loginUrl' => '/users/login',
]);
// Then use sessions if they are active.
$service->loadAuthenticator('Authentication.Session', [
'identifier' => 'Authentication.Password',
]);
$service->loadAuthenticator('Authentication.Session');

// If the user is on the login page, check for a cookie as well.
$service->loadAuthenticator('Authentication.Cookie', [
Expand Down Expand Up @@ -441,9 +442,6 @@ $service->loadAuthenticator('Authentication.Environment', [
]);
```

::: info Added in version 2.10.0
`EnvironmentAuthenticator` was added.
:::

## Events

Expand Down Expand Up @@ -549,9 +547,7 @@ $passwordIdentifier = [
];

// Load the authenticators leaving Basic as the last one.
$service->loadAuthenticator('Authentication.Session', [
'identifier' => $passwordIdentifier,
]);
$service->loadAuthenticator('Authentication.Session');
$service->loadAuthenticator('Authentication.Form', [
'identifier' => $passwordIdentifier,
]);
Expand Down Expand Up @@ -589,7 +585,7 @@ Then in your controller's login method you can use `getLoginRedirect()` to get
the redirect target safely from the query string parameter:

``` php
public function login()
public function login(): ?\Cake\Http\Response
{
$result = $this->Authentication->getResult();

Expand All @@ -600,8 +596,11 @@ public function login()
if (!$target) {
$target = ['controller' => 'Pages', 'action' => 'display', 'home'];
}

return $this->redirect($target);
}

return null;
}
```

Expand All @@ -622,7 +621,7 @@ public function getAuthenticationService(

// Configuration common to both the API and web goes here.

if ($request->getParam('prefix') == 'Api') {
if ($request->getParam('prefix') === 'Api') {
// Include API specific authenticators
} else {
// Web UI specific authenticators.
Expand Down
2 changes: 2 additions & 0 deletions docs/en/contents.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
- [Testing with Authentication](testing)
- [User Impersonation](impersonation)
- [URL Checkers](url-checkers)
- [Redirect Validation](redirect-validation)
- [View Helper](view-helper)
- [Migration from the AuthComponent](migration-from-the-authcomponent)
- [Upgrading from 2.x to 3.x](upgrade-2-to-3)
- [Upgrading from 3.x to 4.x](upgrade-3-to-4)
15 changes: 3 additions & 12 deletions docs/en/identifiers.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
# Identifiers

Identifiers will identify an user or service based on the information
that was extracted from the request by the authenticators. Identifiers
can take options in the `loadIdentifier` method. A holistic example of
Identifiers will identify a user or service based on the information
that was extracted from the request by the authenticators. A holistic example of
using the Password Identifier looks like:

``` php
Expand Down Expand Up @@ -199,15 +198,7 @@ $identifier = [
];
```

Or injected using a setter:

``` php
$resolver = new \App\Identifier\Resolver\CustomResolver();
$identifier = $service->loadIdentifier('Authentication.Password');
$identifier->setResolver($resolver);
```

As of 3.3.0, you should pass the constructed resolver into the identifier:
Or pass the constructed resolver directly into the identifier configuration:

``` php
$resolver = new \App\Identifier\Resolver\CustomResolver();
Expand Down
4 changes: 2 additions & 2 deletions docs/en/identity-object.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,15 +80,15 @@ class User extends Entity implements IdentityInterface
/**
* Authentication\IdentityInterface method
*/
public function getIdentifier()
public function getIdentifier(): array|string|int|null
{
return $this->id;
}

/**
* Authentication\IdentityInterface method
*/
public function getOriginalData()
public function getOriginalData(): \ArrayAccess|array
{
return $this;
}
Expand Down
18 changes: 8 additions & 10 deletions docs/en/impersonation.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
# User Impersonation

::: info Added in version 2.10.0
User impersonation was added.
:::

After deploying your application, you may occasionally need to
'impersonate' another user in order to debug problems that your customers report
or to see the application in the state that your customers are seeing it.
Expand All @@ -16,7 +12,7 @@ user from your application's database:

``` php
// In a controller
public function impersonate()
public function impersonate(): \Cake\Http\Response
{
$this->request->allowMethod(['POST']);

Expand All @@ -29,9 +25,9 @@ public function impersonate()
}

// Fetch the user we want to impersonate.
$targetUser = $this->Users->findById(
$this->request->getData('user_id')
)->firstOrFail();
$targetUser = $this->fetchTable('Users')
->findById($this->request->getData('user_id'))
->firstOrFail();

// Enable impersonation.
$this->Authentication->impersonate($targetUser);
Expand All @@ -50,7 +46,7 @@ back to your previous identity using `AuthenticationComponent`:

``` php
// In a controller
public function revertIdentity()
public function revertIdentity(): \Cake\Http\Response
{
$this->request->allowMethod(['POST']);

Expand All @@ -59,6 +55,8 @@ public function revertIdentity()
throw new NotFoundException();
}
$this->Authentication->stopImpersonating();

return $this->redirect($this->referer());
}
```

Expand All @@ -68,4 +66,4 @@ There are a few limitations to impersonation.

1. Your application must be using the `Session` authenticator.
2. You cannot impersonate another user while impersonation is active. Instead
you must `stopImpersonation()` and then start it again.
you must `stopImpersonating()` and then start it again.
25 changes: 15 additions & 10 deletions docs/en/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ imports:
use Authentication\AuthenticationService;
use Authentication\AuthenticationServiceInterface;
use Authentication\AuthenticationServiceProviderInterface;
use Authentication\Identifier\AbstractIdentifier;
use Authentication\Identifier\PasswordIdentifier;
use Authentication\Middleware\AuthenticationMiddleware;
use Cake\Http\MiddlewareQueue;
use Cake\Routing\Router;
Expand Down Expand Up @@ -93,8 +93,8 @@ public function getAuthenticationService(ServerRequestInterface $request): Authe
]);

$fields = [
AbstractIdentifier::CREDENTIAL_USERNAME => 'email',
AbstractIdentifier::CREDENTIAL_PASSWORD => 'password',
PasswordIdentifier::CREDENTIAL_USERNAME => 'email',
PasswordIdentifier::CREDENTIAL_PASSWORD => 'password',
];

// Load the authenticators. Session should be first.
Expand All @@ -109,7 +109,7 @@ public function getAuthenticationService(ServerRequestInterface $request): Authe
'fields' => $fields,
'loginUrl' => Router::url([
'prefix' => false,
'plugin' => null,
'plugin' => false,
'controller' => 'Users',
'action' => 'login',
]),
Expand All @@ -135,7 +135,7 @@ Next, in your `AppController` load the [Authentication Component](authentication

``` php
// in src/Controller/AppController.php
public function initialize()
public function initialize(): void
{
parent::initialize();

Expand All @@ -156,7 +156,7 @@ $this->Authentication->allowUnauthenticated(['view', 'index']);
## Building a Login Action

Once you have the middleware applied to your application you'll need a way for
users to login. Please ensure your database has been created with the Users table structure used in [tutorial](tutorials-and-examples/cms/database). First generate a Users model and controller with bake:
users to login. Please ensure your database has been created with the Users table structure used in the [CMS tutorial](https://book.cakephp.org/5/en/tutorials-and-examples/cms/database.html). First generate a Users model and controller with bake:

``` bash
bin/cake bake model Users
Expand All @@ -168,17 +168,20 @@ like:

``` php
// in src/Controller/UsersController.php
public function login()
public function login(): ?\Cake\Http\Response
{
$result = $this->Authentication->getResult();
// If the user is logged in send them away.
if ($result && $result->isValid()) {
$target = $this->Authentication->getLoginRedirect() ?? '/home';

return $this->redirect($target);
}
if ($this->request->is('post')) {
$this->Flash->error('Invalid username or password');
}

return null;
}
```

Expand All @@ -188,7 +191,7 @@ unauthenticated users are able to access it:

``` php
// in src/Controller/UsersController.php
public function beforeFilter(\Cake\Event\EventInterface $event)
public function beforeFilter(\Cake\Event\EventInterface $event): void
{
parent::beforeFilter($event);

Expand Down Expand Up @@ -216,9 +219,10 @@ Then add a simple logout action:

``` php
// in src/Controller/UsersController.php
public function logout()
public function logout(): \Cake\Http\Response
{
$this->Authentication->logout();

return $this->redirect(['controller' => 'Users', 'action' => 'login']);
}
```
Expand All @@ -240,9 +244,10 @@ class User extends Entity
// ... other methods

// Automatically hash passwords when they are changed.
protected function _setPassword(string $password)
protected function _setPassword(string $password): string
{
$hasher = new DefaultPasswordHasher();

return $hasher->hash($password);
}
}
Expand Down
6 changes: 2 additions & 4 deletions docs/en/middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function getAuthenticationService(ServerRequestInterface $request): Authe
$path = $request->getPath();

$service = new AuthenticationService();
if (strpos($path, '/api') === 0) {
if (str_starts_with($path, '/api')) {
// Accept API tokens only
$service->loadAuthenticator('Authentication.Token', [
'identifier' => 'Authentication.Token',
Expand All @@ -48,9 +48,7 @@ public function getAuthenticationService(ServerRequestInterface $request): Authe

// Web authentication
// Support sessions and form login.
$service->loadAuthenticator('Authentication.Session', [
'identifier' => 'Authentication.Password',
]);
$service->loadAuthenticator('Authentication.Session');
$service->loadAuthenticator('Authentication.Form', [
'identifier' => 'Authentication.Password',
]);
Expand Down
Loading
Loading