Skip to content
Closed
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
45 changes: 45 additions & 0 deletions docs/en/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,51 @@ setter method::
}
}

JWT Token Generation
====================

To use JWT authentication, we need to generate keys::
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
To use JWT authentication, we need to generate keys::
By default the `JwtAuthenticator` uses `HS256` symmetric key algorithm and uses
the value of `Cake\Utility\Security::salt()` as encryption key.
For enhanced security one can instead use the `RS256` asymmetric key algorithm.
You can generate the required keys for that as follows::


# generate private key
openssl genrsa -out config/jwt.key 1024
# generate public key
openssl rsa -in config/jwt.key -outform PEM -pubout -out config/jwt.pem

To generate a JWT in a ``UsersController``::

public function login()
{
$result = $this->Authentication->getResult();
if ($result->isValid()) {
$privateKey = file_get_contents(CONFIG . '/jwt.key');
$user = $result->getData();
$payload = [
'iss' => 'myapp',
'sub' => $user->id,
'exp' => time() + 60,
];
$json = [
'token' => JWT::encode($payload, $privateKey, 'RS256'),
];
} else {
$this->response = $this->response->withStatus(401);
}
$this->set(compact('json'));
$this->viewBuilder()->setOption('serialize', 'json');
}

Note that this requires setting up your `Applicaion` class as follows::
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Note that this requires setting up your `Applicaion` class as follows::
Note that this requires setting up your `Application` class as follows::


public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
$service = new AuthenticationService();
// ...
$service->loadAuthenticator('Authentication.Jwt', [
'secretKey' => file_get_contents(CONFIG . '/jwt.pem'),
'algorithms' => ['RS256'],
'returnPayload' => false,
]);
}

Further Reading
===============
Expand Down