{"id":13699855,"url":"https://github.com/qbhy/hyperf-auth","last_synced_at":"2025-04-04T08:08:46.983Z","repository":{"id":37829221,"uuid":"266091345","full_name":"qbhy/hyperf-auth","owner":"qbhy","description":"hyperf 的 auth 组件","archived":false,"fork":false,"pushed_at":"2024-01-11T06:30:31.000Z","size":94,"stargazers_count":182,"open_issues_count":3,"forks_count":28,"subscribers_count":1,"default_branch":"master","last_synced_at":"2024-09-17T23:14:44.492Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/qbhy.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-05-22T11:13:50.000Z","updated_at":"2024-09-14T08:45:14.000Z","dependencies_parsed_at":"2023-12-04T13:36:15.394Z","dependency_job_id":"72dac217-e4e9-41d9-9e88-823b45785b65","html_url":"https://github.com/qbhy/hyperf-auth","commit_stats":{"total_commits":87,"total_committers":8,"mean_commits":10.875,"dds":0.3563218390804598,"last_synced_commit":"329f4e34362c9916713f16cdaba22c8b2be31b20"},"previous_names":[],"tags_count":37,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/qbhy%2Fhyperf-auth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/qbhy%2Fhyperf-auth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/qbhy%2Fhyperf-auth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/qbhy%2Fhyperf-auth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/qbhy","download_url":"https://codeload.github.com/qbhy/hyperf-auth/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247142066,"owners_count":20890652,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-02T20:00:44.648Z","updated_at":"2025-04-04T08:08:46.962Z","avatar_url":"https://github.com/qbhy.png","language":"PHP","readme":"# qbhy/hyperf-auth\n\nhyperf 的 auth 组件，目前支持 jwt、session、sso 驱动。用户可以自行扩展。  \n本组件参考了 laravel 的 auth 组件设计，使用体验大体和 laravel 的 auth 差不多。\n\n[![Latest Stable Version](https://poser.pugx.org/96qbhy/hyperf-auth/v/stable)](https://packagist.org/packages/96qbhy/hyperf-auth)\n[![Total Downloads](https://poser.pugx.org/96qbhy/hyperf-auth/downloads)](https://packagist.org/packages/96qbhy/hyperf-auth)\n[![Latest Unstable Version](https://poser.pugx.org/96qbhy/hyperf-auth/v/unstable)](https://packagist.org/packages/96qbhy/hyperf-auth)\n[![License](https://poser.pugx.org/96qbhy/hyperf-auth/license)](https://packagist.org/packages/96qbhy/hyperf-auth)\n[![Monthly Downloads](https://poser.pugx.org/96qbhy/hyperf-auth/d/monthly)](https://packagist.org/packages/96qbhy/hyperf-auth)\n[![Daily Downloads](https://poser.pugx.org/96qbhy/hyperf-auth/d/daily)](https://packagist.org/packages/96qbhy/hyperf-auth)\n\n## 支持的验证方式\n\n* session\n* jwt\n* sso （单点登录，继承自jwt，需要 hyperf/redis，支持多客户端）\n\n\u003e 任何问题请加QQ群提问：873213948\n\n## 安装 - install\n\n```bash\n$ composer require 96qbhy/hyperf-auth\n```\n\n\u003e hyperf 1.1 请使用 ^v1.0 版本\n\n## 配置 - configuration\n\n使用 `Qbhy\\HyperfAuth\\AuthExceptionHandler` ，此步骤可选，开发者可以自行捕捉 `AuthException`  和 `JWTException` 进行处理\n\n```php\n\u003c?php\n// config/autoload/exceptions.php\nreturn [\n    'handler' =\u003e [\n        'http' =\u003e [\n            \\Qbhy\\HyperfAuth\\AuthExceptionHandler::class,\n        ],    \n    ],\n];\n```\n\n发布配置 vendor:publish\n```bash\nphp bin/hyperf.php vendor:publish 96qbhy/hyperf-auth\n```\n\n生成 `.env` 配置项 \n```bash\nphp bin/hyperf.php gen:auth-env\n```\n\n修改 `config/autoload/auth.php`\n\u003e 如不需要自定义 guard、model 和 user provider，则可以不修改\n\n```php\n\u003c?php\n\nuse Doctrine\\Common\\Cache\\FilesystemCache;\nuse Qbhy\\SimpleJwt\\Encoders\\Base64UrlSafeEncoder;\nuse Qbhy\\SimpleJwt\\EncryptAdapters\\PasswordHashEncrypter;\n\nreturn [\n    'default' =\u003e [\n        'guard'=\u003e 'jwt',\n        'provider'=\u003e 'users',\n    ] ,\n    'guards' =\u003e [ // 开发者可以在这里添加自己的 guard ，guard Qbhy\\HyperfAuth\\AuthGuard 接口\n        'sso'=\u003e [\n            // 支持的设备，env配置时用英文逗号隔开\n            'clients' =\u003e explode(',', env('AUTH_SSO_CLIENTS', 'pc')),\n\n            // hyperf/redis 实例\n            'redis' =\u003e function () {\n                return make(\\Hyperf\\Redis\\Redis::class);\n            },\n\n            // 自定义 redis key，必须包含 {uid}，{uid} 会被替换成用户ID\n            'redis_key' =\u003e 'u:token:{uid}',\n\n            'driver' =\u003e Qbhy\\HyperfAuth\\Guard\\SsoGuard::class,\n            // ...$jwtConfig, // 其他配置和 jwt guard的配置一样\n        ],\n        'jwt' =\u003e [\n            'driver' =\u003e Qbhy\\HyperfAuth\\Guard\\JwtGuard::class,\n            'provider' =\u003e 'users',\n\n            // 以下是 simple-jwt 所需的参数，具体配置文档可以看 config/autoload/auth.php\n            'secret' =\u003eenv('JWT_SECRET', 'qbhy/hyperf-auth'),\n            'ttl' =\u003e 60 * 60, // 单位秒\n            'default' =\u003e PasswordHashEncrypter::class,\n            'encoder' =\u003e new Base64UrlSafeEncoder(),\n//            'cache' =\u003e new FilesystemCache(sys_get_temp_dir()), // 如果需要分布式部署，请选择 redis 或者其他支持分布式的缓存驱动\n            'cache' =\u003e function() {\n                return make(Qbhy\\HyperfAuth\\HyperfRedisCache::class);\n            }, \n        ],\n        'session' =\u003e [\n            'driver' =\u003e Qbhy\\HyperfAuth\\Guard\\SessionGuard::class,\n            'provider' =\u003e 'users',\n        ],\n    ],\n    'providers' =\u003e [\n        'users' =\u003e [\n            'driver' =\u003e \\Qbhy\\HyperfAuth\\Provider\\EloquentProvider::class, // user provider 需要实现 Qbhy\\HyperfAuth\\UserProvider 接口\n            'model' =\u003e App\\Model\\User::class, //  需要实现 Qbhy\\HyperfAuth\\Authenticatable 接口\n        ],\n    ],\n];\n```\n\n## 使用 - usage\n\n\u003e 以下是伪代码，仅供参考。Auth 注解可以用于类或者方法。\n\n```php\n\u003c?php\ndeclare(strict_types=1);\n\nnamespace App\\Controller;\n\nuse Hyperf\\Di\\Annotation\\Inject;\nuse Hyperf\\HttpServer\\Annotation\\Controller;\nuse Hyperf\\HttpServer\\Annotation\\GetMapping;\nuse Qbhy\\HyperfAuth\\Annotation\\Auth;\nuse Qbhy\\HyperfAuth\\AuthManager;\n\n/**\n* @Controller\n* Class IndexController\n*/\nclass IndexController extends AbstractController\n{\n  /**\n   * @Inject\n   * @var AuthManager\n   */\n  protected $auth;\n\n  /**\n   * @GetMapping(path=\"/login\")\n   * @return array\n   */\n  public function login()\n  {\n      /** @var User $user */\n      $user = User::query()-\u003efirstOrCreate(['name' =\u003e 'test', 'avatar' =\u003e 'avatar']);\n      return [\n          'status' =\u003e $this-\u003eauth-\u003eguard('session')-\u003elogin($user),\n      ];\n  }\n  \n  /**\n   * @GetMapping(path=\"/sso/login\")\n   * @return array\n   */\n  public function ssoLogin()\n  {\n      /** @var User $user */\n      $user = User::query()-\u003efirstOrCreate(['name' =\u003e 'test', 'avatar' =\u003e 'avatar']);\n      return [\n          'token' =\u003e $this-\u003eauth-\u003eguard('sso')-\u003elogin($user, [],  'pc'), // sso 方法支持第二个参数，传定义好的客户端\n      ];\n  }\n\n  /**\n   * @Auth(\"session\")\n   * @GetMapping(path=\"/logout\")\n   */\n  public function logout()\n  {\n      $this-\u003eauth-\u003eguard('session')-\u003elogout();\n      return 'logout ok';\n  }\n\n  /**\n   * 使用 Auth 注解可以保证该方法必须通过某个 guard 的授权，支持同时传多个 guard，不传参数使用默认 guard\n   * @Auth(\"session\")\n   * @GetMapping(path=\"/user\")\n   * @return string\n   */\n  public function user()\n  {\n      $user = $this-\u003eauth-\u003eguard('session')-\u003euser();\n      return 'hello '.$user-\u003ename;\n  }\n}\n```\n\n除了上面的 Auth 注解用法，还支持中间件用法\n\n```php\n\u003c?php\n\ndeclare(strict_types=1);\n\nnamespace App\\Controller;\n\nuse Hyperf\\HttpServer\\Annotation\\Middleware;\nuse Qbhy\\HyperfAuth\\AuthMiddleware; \nuse Hyperf\\Di\\Annotation\\Inject;\nuse Hyperf\\HttpServer\\Annotation\\GetMapping;\nuse Qbhy\\HyperfAuth\\AuthManager;\n\n/**\n* @Middleware(AuthMiddleware::class)\n* Class IndexController\n*/\nclass IndexController extends AbstractController\n{\n  /**\n   * @Inject\n   * @var AuthManager\n   */\n  protected $auth;\n  \n  /**\n   * @GetMapping(path=\"/user\")\n   * @return string\n   */\n  public function user()\n  {\n      $user = $this-\u003eauth-\u003eguard()-\u003euser();\n      return 'hello '.$user-\u003ename;\n  }\n}\n```\n\n由于 hyperf 还不支持中间件传参，所以 `Qbhy\\HyperfAuth\\AuthMiddleware` 中间件只支持默认guard校验  \n但是开发者可以继承该中间自行扩展。或者直接使用 Auth 注解进行自定义 guard 校验，与中间件的效果是一致的。\n\n```php\n\u003c?php\n\ndeclare(strict_types=1);\n\nuse Qbhy\\HyperfAuth\\AuthMiddleware; \n\nclass SessionAuthMiddleware extends AuthMiddleware { \n    protected $guards = ['session']; // 支持多个 guard\n\n }\n```\n\n## 更多用法 - API\n\n```php\n\u003c?php\n\n$auth = auth(); // 控制器内也可以通过 @Inject 注入\n\n$user = new \\HyperfTest\\DemoUser(1);\n\n// 直接调用 AuthGuard 方法，这种情况下会获取 默认 guard 然后调用 guard 的对应方法\n$auth-\u003elogin($user); // 默认使用 jwt 驱动，该方法将返回 token 字符串\n$auth-\u003elogout(); // 退出登录\n$auth-\u003echeck(); // 检查是否登录\n$auth-\u003eid(); // 获取当前登录用户的id，无需查数据库\n$auth-\u003eguest(); // 是否游客/是否未登录\n$auth-\u003euser(); // 若登录返回当前登录用户，否则返回null\n\n/** @var \\Qbhy\\HyperfAuth\\Guard\\JwtGuard $jwtGuard */\n$jwtGuard = $auth-\u003eguard('jwt');\n$jwtGuard-\u003euser('your token or null'); // jwt 驱动支持手动传入 token，如不传或者传null则从 request 中解析\n$jwtGuard-\u003echeck('your token or null');\n$jwtGuard-\u003eid('your token or null'); // 无需查数据库\n$jwtGuard-\u003eguest('your token or null');\n$jwtGuard-\u003erefresh('your token or null'); // 该方法返回新的 token 或者 null\n$jwtGuard-\u003elogin($user, ['sub' =\u003e 'qbhy0715','iss' =\u003e 'hyperf-auth',]); // 自定义payload\n$jwtGuard-\u003egetPayload('your token or null'); // 获取自定义 payload\n\n$auth-\u003eguard()-\u003elogin($user); // guard 方法不传参数或者传null都将使用默认值\n\n// 使用 session 驱动需要安装 hyperf/session 并启用 session\n$auth-\u003eguard('session')-\u003elogin($user); // guard 方法不传参数或者传null都会获取默认值\n```\n\n\u003e 注意事项：使用 jwt 驱动且令牌异常的情况下调用 user 方法，会抛出相应的异常，需要自行捕捉处理，不想抛异常，可以调用 check 进行判断。\n\n## 扩展 - extension\n\n由于本组件参考了 laravel auth 的设计，所以 guard 和 user provider 的扩展也和 laravel 类似。只需要实现对应接口即可。\n\n* guard ===\u003e Qbhy\\HyperfAuth\\AuthGuard\n* user provider ===\u003e Qbhy\\HyperfAuth\\UserProvider\n\n\u003e 扩展教程请移步 [hyperf教程之hyperf-auth高级用法](https://mp.weixin.qq.com/s/jlbbN6zhWEVteimpi0mLjg)\n\nhttps://github.com/qbhy/hyperf-auth  \nqbhy0715@qq.com  ","funding_links":[],"categories":["Frameworks"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fqbhy%2Fhyperf-auth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fqbhy%2Fhyperf-auth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fqbhy%2Fhyperf-auth/lists"}