Skip to content

Instantly share code, notes, and snippets.

@sebastianknopf
Created July 10, 2019 21:06
Show Gist options
  • Save sebastianknopf/1ef776869c2500f2b122dbe338b0a441 to your computer and use it in GitHub Desktop.
Save sebastianknopf/1ef776869c2500f2b122dbe338b0a441 to your computer and use it in GitHub Desktop.
Using JwtAuthenticator in CakePHP's Authentication Plugin
// to use the JwtAuthenticator in a CakePHP application you first have load the corresponding
// authenticator in your Application::getAuthenticationService(...)
$service->loadAuthenticator('Authentication.Jwt', [
'returnPayload' => false
]);
// The parameter 'returnPayload' is set to true by default - If you want your visitor using the JWT run trough a full authentication
// process, you should set it to false.
// If you want to implement the full authentication process, you also have to
// load the identifier called 'JwtSubject'. You don't have to change any options here for default usage.
$service->loadIdentifier('Authentication.JwtSubject');
// To grant a visitor access to a protected page, you only have to put a query param named 'token' at the end of the URL which
// which contains the JWT you generated before. The validation process will run in the middleware automatically, but how to
// create such a JWT which can be processed by CakePHP? Sadly there's no information about that in the documentation, so let's
// go here...!
// The authentication plugin of CakePHP uses the PHP-JWT implementation from Firebase. The documentation there is kept
// very clearly and tells you everything you need to create a valid JWT.
use Cake\Utility\Security;
use Firebase\JWT\JWT;
$payload = [
IdentifierInterface::CREDENTIAL_JWT_SUBJECT => [
'id' => $user->id
]
];
$jwt = JWT::encode($payload, Security::getSalt());
// The payload should only contain an array with the key specified by the authentication Plugin. This key points to an array
// containing only the ID (the primary key) of your Identity object. No more information are required to run through the authentication
// process. The JWT can be created in any controller.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment