ホームページ  >  記事  >  PHPフレームワーク  >  認証に Hyperf フレームワークを使用する方法

認証に Hyperf フレームワークを使用する方法

PHPz
PHPzオリジナル
2023-10-24 10:01:01598ブラウズ

認証に Hyperf フレームワークを使用する方法

認証に Hyperf フレームワークを使用する方法

最新の Web アプリケーションでは、ユーザー認証は非常に重要な機能です。機密情報を保護し、アプリケーションのセキュリティを確保するために、認証により、認証されたユーザーのみが制限されたリソースにアクセスできるようになります。

Hyperf は、Swoole をベースにした高性能 PHP フレームワークで、多くの最新かつ効率的な機能とツールを提供します。 Hyperf フレームワークでは複数の方法で ID 認証を実装できますが、一般的に使用される 2 つの方法を以下に紹介します。

  1. JWT (JSON Web トークン) の使用

JWT は、通信当事者間で情報を安全に送信するための簡潔で自己完結型の方法を定義するオープン スタンダード (RFC 7519) です。 。 Hyperf フレームワークでは、lcobucci/jwt 拡張ライブラリを使用して、JWT の生成と検証を実現できます。

まず、lcobucci/jwt ライブラリの依存関係をcomposer.json ファイルに追加する必要があります:

"require": {
    "lcobucci/jwt": "^3.4"
}

次に、composer update コマンドを実行します。依存関係をインストールします。

次に、JWT を生成および検証するための JwtAuthenticator クラスを作成できます。

<?php

declare(strict_types=1);

namespace AppAuth;

use HyperfExtAuthAuthenticatable;
use HyperfExtAuthContractsAuthenticatorInterface;
use LcobucciJWTConfiguration;
use LcobucciJWTToken;

class JwtAuthenticator implements AuthenticatorInterface
{
    private Configuration $configuration;

    public function __construct(Configuration $configuration)
    {
        $this->configuration = $configuration;
    }

    public function validateToken(string $token): bool
    {
        $parsedToken = $this->configuration->parser()->parse($token);
        $isVerified = $this->configuration->validator()->validate($parsedToken, ...$this->configuration->validationConstraints());
        
        return $isVerified;
    }

    public function generateToken(Authenticatable $user): string
    {
        $builder = $this->configuration->createBuilder();
        $builder->issuedBy('your_issuer')
            ->issuedAt(new DateTimeImmutable())
            ->expiresAt((new DateTimeImmutable())->modify('+1 hour'))
            ->withClaim('sub', (string) $user->getAuthIdentifier());
        
        $token = $builder->getToken($this->configuration->signer(), $this->configuration->signingKey());
        
        return $token->toString();
    }
}

次に、それを Hyperf フレームワークのコンテナーに登録する必要があります。 JwtAuthenticator クラス:

HyperfUtilsApplicationContext::getContainer()->define(AppAuthJwtAuthenticator::class, function (PsrContainerContainerInterface $container) {
    $configuration = LcobucciJWTConfiguration::forAsymmetricSigner(
        new LcobucciJWTSignerRsaSha256(),
        LcobucciJWTSignerKeyLocalFileReference::file('path/to/private/key.pem')
    );

    return new AppAuthJwtAuthenticator($configuration);
});

最後に、認証を必要とするルートまたはコントローラー メソッドで、

JwtAuthenticator クラスを使用してユーザーの JWT を検証できます:

<?php

declare(strict_types=1);

namespace AppController;

use AppAuthJwtAuthenticator;
use HyperfHttpServerAnnotationController;
use HyperfHttpServerAnnotationRequestMapping;

/**
 * @Controller(prefix="/api")
 */
class ApiController
{
    private JwtAuthenticator $authenticator;

    public function __construct(JwtAuthenticator $authenticator)
    {
        $this->authenticator = $authenticator;
    }

    /**
     * @RequestMapping(path="profile", methods="GET")
     */
    public function profile()
    {
        $token = $this->request->getHeader('Authorization')[0] ?? '';
        $token = str_replace('Bearer ', '', $token);
        
        if (!$this->authenticator->validateToken($token)) {
            // Token验证失败,返回错误响应
            return 'Unauthorized';
        }

        // Token验证成功,返回用户信息
        return $this->authenticator->getUserByToken($token);
    }
}

    セッションの使用
JWT 認証に加えて、Hyperf フレームワークは ID 認証のためのセッションの使用もサポートしています。設定ファイルを通じてセッション認証機能を有効にすることができます。

まず、設定ファイル

config/autoload/session.php で対応する設定を行う必要があります。例:

return [
    'handler' => [
        'class' => HyperfRedisSessionHandler::class,
        'options' => [
            'pool' => 'default',
        ],
    ],
];

次に、ルーティングまたはコントロールで、対応する設定を行う必要があります。認証が必要なサーバー メソッドでは、Hyperf フレームワークによって提供される

AuthManager クラスを使用してユーザーのセッションを認証できます。

<?php

declare(strict_types=1);

namespace AppController;

use HyperfHttpServerAnnotationController;
use HyperfHttpServerAnnotationRequestMapping;
use HyperfExtAuthContractsAuthManagerInterface;

/**
 * @Controller(prefix="/api")
 */
class ApiController
{
    private AuthManagerInterface $authManager;

    public function __construct(AuthManagerInterface $authManager)
    {
        $this->authManager = $authManager;
    }

    /**
     * @RequestMapping(path="profile", methods="GET")
     */
    public function profile()
    {
        if (!$this->authManager->check()) {
            // 用户未登录,返回错误响应
            return 'Unauthorized';
        }

        // 用户已登录,返回用户信息
        return $this->authManager->user();
    }
}

上記のコードでは、

AuthManagerInterface インターフェースは多くの認証を提供し、実際のニーズに応じてユーザー操作メソッドを呼び出すことができます。

上記は、Hyperf フレームワークを使用した ID 認証の 2 つの一般的な方法であり、JWT またはセッションを通じてユーザー認証を実装します。実際のニーズとプロジェクトの特性に基づいて、アプリケーションのセキュリティとユーザー エクスペリエンスを確保するための適切な方法を選択します。実際の開発では、フレームワークが提供するドキュメントとサンプル コードに基づいて、高度な使用方法とベスト プラクティスについて詳しく学ぶことができます。

以上が認証に Hyperf フレームワークを使用する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。