In this post, we will learn how to integrate the JWT (JSON Web Tokens) middleware in Lithe, providing robust and secure authentication for your API. The use of JWT allows you to authenticate users and protect sensitive routes simply and efficiently.
What is JWT?
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for transmitting information between parties as a JSON object. These tokens can be used for authentication, allowing you to maintain a user's session without the need to store information on the server. JWT consists of three parts: header, payload, and signature.
Step 1: Setting Up the Environment
- Installing Lithe First, install Lithe if you haven't done so yet. Run the following command in the terminal:
composer create-project lithephp/lithephp project-name
cd project-name
Step 2: Installing the JWT Middleware
-
Installing the JWT Package
To use the JWT middleware, you need to install the
lithemod/jwt
package. Execute:
composer require lithemod/jwt
-
Starting the Application
Open the main file
src/App.php
and add the following code to start the application:
use function Lithe\Orbis\Http\Router\router;
$app = new \Lithe\App;
$app->use('/api', router(__DIR__ . '/routes/api'));
$app->listen();
Step 3: Protecting Routes with JWT
-
Creating a Protected Route
In your Lithe project, you can create a route that requires authentication. For example, create a file named
src/routes/api.php
and add:
use Lithe\Http\{Request, Response};
use function Lithe\Orbis\Http\Router\{get};
$auth = new \Lithe\Auth\JWT();
get('/protected', $auth, function(Request $req, Response $res) {
$user = $req->user; // User data
return $res->json(['message' => 'This is a protected content!']);
});
Step 4: Generating JWT Tokens
-
Creating a Login Route
Create a route for authentication where users can obtain a JWT token. Add the following in the same file
src/routes/api.php
:
use Lithe\Http\{Request, Response};
use function Lithe\Orbis\Http\Router\{post};
post('/login', function(Request $req, Response $res) {
$body = $req->body(); // Assuming the request body contains 'username' and 'password'
// Here you should validate the user's credentials (simplified example)
if ($body->username === 'admin' && $body->password === 'password') {
$user = ['id' => 1]; // Example user
$token = (new \Lithe\Auth\JWT())->generateToken($user);
return $res->send(['token' => $token]);
}
return $res->status(401)->json(['message' => 'Invalid credentials']);
});
Final Considerations
With this, you have successfully integrated the JWT middleware into Lithe, allowing for secure authentication and protection of sensitive routes. It is important to remember that when using JWT, you should define a secure and secret key when instantiating the JWT object by passing it as the first parameter: new JWT('your_secret_key')
. This key should be complex and kept secret to prevent fraud.
Now you can expand your application as needed and implement additional features such as token revocation and session management.
To dive deeper into JWT, you can check out the official documentation here.
Feel free to share your experiences and questions in the comments!
Top comments (0)