fx / hyperf-http-auth
在hyperf中使用认证,类似于laravel
Requires
- php: >=7.3
- ext-json: *
- ext-swoole: >=4.5
- hyperf/cache: 2.1.*
- hyperf/config: 2.1.*
- hyperf/di: 2.1.*
- hyperf/framework: 2.1.*
- hyperf/utils: 2.1.*
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.14
- hyperf/testing: 2.1.*
- phpstan/phpstan: *
- swoole/ide-helper: ^4.5
Suggests
- fx/eloquent-provider: require fx/eloquent-provider(^3.0) to use eloquent user provider
- fx/session-guard: require fx/session-guard(^3.0) to use session guard provider
README
-
仿照laravel auth组件,抽离其中的核心逻辑,形成当前扩展包
-
将UserProvider与Guard抽离出去,形成单独扩展包,方便扩展,默认使用以下组合
-
fx/eloquent-provider 使用Eloquent ORM;
-
fx/session-guard 使用session作为guard;
-
-
从2.0版本开始,需要手动安装
fx/eloquent-provider
和fx/session-guard
使用
安装
composer require fx/hyperf-http-auth:"^1.1"
发布配置文件
php bin/hyperf.php vendor:publish fx/hyperf-http-auth
创建用户model并修改为以下配置
<?php declare (strict_types=1); namespace App\Model; use Fx\HyperfHttpAuth\Contract\Authenticatable; use Hyperf\DbConnection\Model\Model; class User extends Model implements Authenticatable { use \Fx\HyperfHttpAuth\Authenticatable; }
配置依赖扩展
fx/session-guard
依赖hyperf/session
需要正确配置其相关内容 官方文档
在controller中使用
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Model\User;
use Fx\HyperfHttpAuth\Contract\HttpAuthContract;
use Hyperf\Di\Annotation\Inject;
class IndexController extends AbstractController
{
/**
* @Inject()
* @var HttpAuthContract
*/
protected $auth;
public function index()
{
return $this->data();
}
/**
* 登录
*/
public function login()
{
/** 方式 1 */
// 等价于 auth()->login(User::first());
$this->auth->login(User::first());
/** 方式 2 */
// 等价于 auth()->attempt(['email' => 'xxx', 'password' => '123456']);
$this->auth->attempt(['email' => 'xxx', 'password' => '123456']);
return $this->data();
}
/**
* 登出
*/
public function logout()
{
// 等价于 auth()->logout();
$this->auth->logout();
return $this->data();
}
protected function data()
{
return [
'user' => auth()->user(),
'is_login' => auth()->check(),
];
}
}
扩展UserProvider
-
实现
Fx\HyperfHttpAuth\Contract\UserProvider
这个抽象类 -
添加
Fx\HyperfHttpAuth\Annotation\UserProviderAnnotation
类注解,该注解接收一个参数,为该驱动的名称
扩展Guard
-
实现
Fx\HyperfHttpAuth\Contract\StatefulGuard
这个抽象类 -
添加
Fx\HyperfHttpAuth\Annotation\GuardAnnotation
类注解,该注解接收一个参数,为该驱动的名称 -
可参考:fx/session-guard
更新说明
-
2020-05-12: 修复session guard中引用cookie的问题,该问题导致登录时无法使用
记住我
-
2019-12-26: 添加
Fx\HyperfHttpAuth\AuthenticateMiddleware
中间件,未认证通过会抛出Fx\HyperfHttpAuth\Exception\AuthenticationException
-
2019-12-27: 添加自动化测试
-
2020-01-07: 修复:
Fx\HyperfHttpAuth\Contract\Guard::name()
,更新自动化测试 -
2020-08-17: 修复收集器无法收集到自定义的注解,该问题会导致
Guard
和UserProvider
无法正常使用