Little JWT includes custom validation rules for validating tokens passed as form inputs. This allows the token to be validated in the controller, rather than somewhere else like the middleware.
A ValidToken
rule instance allows for tokens to be validated similiar to how tokens are validated using the validateToken
method.
Create a ValidToken
instance by passing a callback function (and maybe a boolean
parameter indicating if the default validatable should be used) to the constructor:
use LittleApps\LittleJWT\Laravel\Rules\ValidToken;
use LittleApps\LittleJWT\Validation\Validator;
$callback = function (Validator $validator) {
/* ... */
};
$applyDefault = false;
$rule = new ValidToken($callback, $applyDefault);
A callback array referencing a validatable can also be passed as the first parameter:
use LittleApps\LittleJWT\Laravel\Rules\ValidToken;
use LittleApps\LittleJWT\Validation\Validator;
$validatable = new MyValidator();
$callback = [$validatable, 'validate'];
// $applyDefault defaults to true if not passed.
$rule = new ValidToken($callback);
Attach the validation rule instance to a validator along with any other Laravel validation rules:
use Illuminate\Support\Facades\Validator;
use LittleApps\LittleJWT\Laravel\Rules\ValidToken;
$validator = Validator::make($request->all(), [
'token' => [
'required',
new ValidToken($callback, $applyDefault)
]
]);
See Laravel's documentation on Validation for more information on working with a Validator instance and different methods of validating inputs.
Little JWT provides the implicit validtoken
rule as an alternative to a ValidToken
rule instance. It's important to note that it is an implicit rule, meaning it implies the token is required before it can be validated.
A comma seperated list can be included to specify which validatables to use:
use Illuminate\Support\Facades\Validator;
use LittleApps\LittleJWT\Laravel\Rules\ValidToken;
$validator = Validator::make($request->all(), [
'token' => 'validtoken:default,guard'
]);
If a comma seperated list is not included, the default validatable is used:
use Illuminate\Support\Facades\Validator;
use LittleApps\LittleJWT\Laravel\Rules\ValidToken;
$validator = Validator::make($request->all(), [
'token' => 'validtoken'
]);
The ValidateRuleTest.php file contains further examples on running the rules through Laravel's validator.