JWT authentication in Yii2

1. Install the firebase/php-jwt package using composer:

composer require firebase/php-jwt

2. Create a JwtHelper class that will handle the JWT authentication:

namespace app\components;

use Firebase\JWT\JWT;
use yii\base\Component;

class JwtHelper extends Component
{
    private $key = 'YOUR_SECRET_KEY';
    private $algorithm = 'HS256';
    private $expire = 3600;
    
    public function generateToken($payload)
    {
        $payload['exp'] = time() + $this->expire;
        return JWT::encode($payload, $this->key, $this->algorithm);
    }
    
    public function validateToken($token)
    {
        try {
            $decoded = JWT::decode($token, $this->key, [$this->algorithm]);
            return (array) $decoded;
        } catch (\Exception $e) {
            return false;
        }
    }
}

This class contains two methods: generateToken() for generating a JWT token and validateToken() for validating the token.

3. In your Yii2 application configuration file (config/web.php), configure the JWT helper as a component:

return [
    // ...
    'components' => [
        // ...
        'jwt' => [
            'class' => 'app\components\JwtHelper',
        ],
    ],
];

4. In your authentication controller action, generate a JWT token and return it to the client:

public function actionLogin()
{
    // Perform authentication...
    
    $payload = [
        'user_id' => $user->id,
        'username' => $user->username,
        'email' => $user->email,
    ];
    $token = Yii::$app->jwt->generateToken($payload);
    return ['token' => $token];
}

5. In your controller actions that require authentication, validate the JWT token:

public function actionProtected()
{
    $authHeader = Yii::$app->request->headers->get('Authorization');
    $token = str_replace('Bearer ', '', $authHeader);
    $payload = Yii::$app->jwt->validateToken($token);
    if (!$payload) {
        throw new \yii\web\UnauthorizedHttpException();
    }
    // ...
}

This example validates the token by retrieving it from the Authorization header and passing it to the validateToken() method.

By following these steps, you can use JWT authentication in your Yii2 application. This is just a basic example, and you may need to modify it depending on your specific requirements.

Komentar

Postingan populer dari blog ini

Node.js Telegram Bot API send an image with text

Node.js Telegram BOT retrieve data from API

WhatsApp Web login QR code in an HTML page using whatsapp-web.js