Slim PHP is one of my favouriteweb frameworks, it's simple to learn, lightweight, and great for building small websites and applications.
One of the best use cases forSlim PHP is when you need to build a small API with a handful of endpoints. In this scenario you may need to add a layer of security to authorise resource requests. A great way to do this is withJSON Web Tokens.
JWTs allow you to provide users with access to API endpoints and their resources in a granular manner. Access can be time limited, restricted to certain user groups and more.
The easiest way to add JWT authorisation to Slim PHP is via the libraryPSR-JWT. It is aPSR 7 / 15 compliant JWT creation and validation library, which works perfectly with Slim PHP as it is also PSR 7 / 15 compliant.
PSR-JWT is built on top ofReallySimpleJWT and it exposes authorisation middleware which can easily be added to Slim PHP's routing system.
Here's an example of how to add the middleware to a Slim PHP route:
require'../../vendor/autoload.php';$app->get('/route/example',function(Request$request,Response$response){$response->getBody()->write("JSON Web Token is Valid!");return$response;})->add(\PsrJwt\Factory\JwtMiddleware::json('Secret123!456$','jwt','Authorisation Failed'));
It's literally a few lines of code, you just pass theJwtMiddleware::json()
method a token secret, a request key and a response message. If the JSON Web Token passed with the request is invalid you'll see the response message and if it is valid the route will load as expected.
PSR-JWT is also completely customisable, you can even use your ownhandlers to define how authorisation works and what the response should be. You can also use the library to generate JSON web tokens.
require'vendor/autoload.php';$factory=new\PsrJwt\Factory\Jwt();$builder=$factory->builder();$token=$builder->setSecret('!secReT$123*')->setPayloadClaim('uid',12)->build();echo$token->getToken();
Have a read of thedocumentation to find out more about all the features available in PSR-JWT. Also if you want to understand JSON Web Tokens in more detail I suggest you giveRFC 7519 andRFC 6750 a read. If you have any questions feel free to drop me a message on Twitter@RobDWaller.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse