>  기사  >  PHP 프레임워크  >  인증을 위해 Hyperf 프레임워크를 사용하는 방법

인증을 위해 Hyperf 프레임워크를 사용하는 방법

PHPz
PHPz원래의
2023-10-24 10:01:01598검색

인증을 위해 Hyperf 프레임워크를 사용하는 방법

인증을 위해 Hyperf 프레임워크를 사용하는 방법

최신 웹 애플리케이션에서 사용자 인증은 매우 중요한 기능입니다. 중요한 정보를 보호하고 애플리케이션 보안을 보장하기 위해 인증을 통해 인증된 사용자만 제한된 리소스에 액세스할 수 있도록 합니다.

Hyperf는 Swoole을 기반으로 하는 고성능 PHP 프레임워크로, 현대적이고 효율적인 다양한 기능과 도구를 제공합니다. Hyperf 프레임워크에서는 여러 가지 방법을 사용하여 신원 인증을 구현할 수 있습니다. 일반적으로 사용되는 두 가지 방법이 아래에 소개됩니다.

  1. JWT(JSON 웹 토큰) 사용

JWT는 통신 당사자 간에 정보를 안전하게 전송하기 위한 간결하고 독립적인 방법을 정의하는 개방형 표준(RFC 7519)입니다. Hyperf 프레임워크에서는 lcobucci/jwt 확장 라이브러리를 사용하여 JWT 생성 및 검증을 달성할 수 있습니다. lcobucci/jwt扩展库来实现JWT的生成和验证。

首先,我们需要在composer.json文件中添加lcobucci/jwt库的依赖项:

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

然后执行composer update命令安装依赖项。

接下来,我们可以创建一个JwtAuthenticator类,用于生成和验证JWT:

<?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);
    }
}
  1. 使用Session

除了JWT认证,Hyperf框架也支持使用Session进行身份认证。我们可以通过配置文件来启用Session认证功能。

首先,我们需要在配置文件config/autoload/session.php中进行相应的配置,例如:

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

然后,在需要认证的路由或控制器方法中,我们可以使用Hyperf框架提供的AuthManager类来验证用户的Session:

<?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

먼저, 작곡가.json 파일에 lcobucci/jwt 라이브러리의 종속성을 추가해야 합니다.

rrreee

그런 다음 composer update 명령을 실행하여 종속성을 설치합니다. . 🎜🎜다음으로 JWT를 생성하고 검증하기 위한 JwtAuthenticator 클래스를 생성할 수 있습니다. 🎜rrreee🎜그런 다음 Hyperf 프레임워크의 컨테이너에 JwtAuthenticator 클래스를 등록해야 합니다. 🎜rrreee🎜마지막으로 인증이 필요한 경로 또는 컨트롤러 메서드에서 JwtAuthenticator 클래스를 사용하여 사용자의 JWT를 확인할 수 있습니다. 🎜rrreee
    🎜Use Session🎜🎜🎜 JWT 인증 외에도 Hyperf 프레임워크는 ID 인증을 위해 세션 사용을 지원합니다. 구성 파일을 통해 세션 인증 기능을 활성화할 수 있습니다. 🎜🎜먼저 구성 파일 config/autoload/session.php에서 해당 구성을 만들어야 합니다. 예: 🎜rrreee🎜그런 다음 인증이 필요한 경로 또는 컨트롤러 메서드에서 다음을 수행할 수 있습니다. Hyperf 프레임워크에서 제공하는 AuthManager 클래스를 사용하여 사용자 세션을 확인합니다. 🎜rrreee🎜위 코드에서 AuthManagerInterface 인터페이스는 인증 및 사용자 작업을 위한 다양한 방법을 제공합니다. , 실제 필요에 따라 전화를 걸 수 있습니다. 🎜🎜위는 JWT 또는 세션을 사용하여 사용자 인증을 구현하는 Hyperf 프레임워크를 사용하는 두 가지 일반적인 ID 인증 방법입니다. 실제 요구 사항과 프로젝트 특성에 따라 적절한 방법을 선택하여 애플리케이션 보안과 사용자 경험을 보장합니다. 실제 개발에서는 프레임워크에서 제공하는 문서와 샘플 코드를 기반으로 고급 사용법과 모범 사례에 대해 자세히 알아볼 수 있습니다. 🎜

위 내용은 인증을 위해 Hyperf 프레임워크를 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.