Home >Backend Development >PHP Tutorial >Integrating JWT Authentication into Lithe

Integrating JWT Authentication into Lithe

Patricia Arquette
Patricia ArquetteOriginal
2024-11-04 21:47:02709browse

Integrando Autenticação JWT no Lithe

In this post, we will learn how to integrate JWT (JSON Web Tokens) middleware into Lithe, providing robust and secure authentication for your API. Using JWT allows you to authenticate users and secure sensitive routes simply and efficiently.

What is JWT?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact, self-contained method 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 needing to store information on the server. JWT is composed of three parts: header, payload and signature.

Step 1: Configuring the Environment

  1. Lithe Installation First, install Lithe if you haven't already. Run the following command in the terminal:
composer create-project lithephp/lithephp nome-do-projeto
cd nome-do-projeto

Step 2: Installing the JWT Middleware

  1. Installing the JWT Package To use the JWT middleware, you need to install the lithemod/jwt package. Run:
composer require lithemod/jwt
  1. Starting the application Open the main src/App.php file 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: Securing Routes with JWT

  1. Creating a Protected Route In your Lithe project, you can create a route that requires authentication. For example, create a file called 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) {
    return $res->json(['message' => 'Este é um conteúdo protegido!']);
});

Step 4: Generating JWT Tokens

  1. Creating a Login Route Create a route for authentication where users can obtain a JWT token. Add the following in the same src/routes/api.php file:
use Lithe\Http\{Request, Response};
use function Lithe\Orbis\Http\Router\{post};

post('/login', function(Request $req, Response $res) {
     $body = $req->body(); // Supondo que o corpo da requisição contenha 'username' e 'password'

    // Aqui você deve validar as credenciais do usuário (exemplo simplificado)
    if ($body->username === 'admin' && $body->password === 'senha') {
        $user = ['id' => 1]; // Exemplo de usuário
        $token = (new \Lithe\Auth\JWT())->generateToken($user);
        return $res->send(['token' => $token]);
    }

    return $res->status(401)->json(['message' => 'Credenciais inválidas']);
});

Of course! Here is the updated section with information about setting a secure and secret key when using JWT:


Final Considerations

With this, you have successfully integrated JWT middleware with Lithe, enabling secure authentication and protection of sensitive routes. It is important to remember that when using JWT, you must define a secure and secret key when instantiating the JWT object, passing it as the first parameter: new JWT('your_secret_key'). This key must be complex and kept secret to avoid fraud.

Now you can expand your application as needed and implement additional functionality such as token revocation and session management.

To learn more about JWT, you can check out the official documentation here.

Feel free to share your experiences and questions in the comments!

The above is the detailed content of Integrating JWT Authentication into Lithe. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn