{"id":19621620,"url":"https://github.com/pkg6/think-auth","last_synced_at":"2025-12-12T19:59:45.037Z","repository":{"id":57676573,"uuid":"488795094","full_name":"pkg6/think-auth","owner":"pkg6","description":"thinkphp 用户认证 Auth","archived":false,"fork":false,"pushed_at":"2024-12-13T11:14:39.000Z","size":229,"stargazers_count":8,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"develop","last_synced_at":"2025-11-16T07:07:26.971Z","etag":null,"topics":["auth","jwt","jwt-token","rbac","thinkphp"],"latest_commit_sha":null,"homepage":"https://packagist.org/packages/tp5er/think-auth","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/pkg6.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,"zenodo":null}},"created_at":"2022-05-05T01:33:13.000Z","updated_at":"2024-12-16T07:41:41.000Z","dependencies_parsed_at":"2024-05-28T05:38:14.824Z","dependency_job_id":"57560d7f-a688-4190-ac0d-fc8564225509","html_url":"https://github.com/pkg6/think-auth","commit_stats":null,"previous_names":[],"tags_count":21,"template":false,"template_full_name":null,"purl":"pkg:github/pkg6/think-auth","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pkg6%2Fthink-auth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pkg6%2Fthink-auth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pkg6%2Fthink-auth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pkg6%2Fthink-auth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pkg6","download_url":"https://codeload.github.com/pkg6/think-auth/tar.gz/refs/heads/develop","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pkg6%2Fthink-auth/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":27690484,"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","status":"online","status_checked_at":"2025-12-12T02:00:06.775Z","response_time":129,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":["auth","jwt","jwt-token","rbac","thinkphp"],"created_at":"2024-11-11T11:23:44.838Z","updated_at":"2025-12-12T19:59:45.015Z","avatar_url":"https://github.com/pkg6.png","language":"PHP","readme":"[![Latest Stable Version](http://poser.pugx.org/tp5er/think-auth/v)](https://packagist.org/packages/tp5er/think-auth) [![Total Downloads](http://poser.pugx.org/tp5er/think-auth/downloads)](https://packagist.org/packages/tp5er/think-auth) [![Latest Unstable Version](http://poser.pugx.org/tp5er/think-auth/v/unstable)](https://packagist.org/packages/tp5er/think-auth) [![License](http://poser.pugx.org/tp5er/think-auth/license)](https://packagist.org/packages/tp5er/think-auth) [![PHP Version Require](http://poser.pugx.org/tp5er/think-auth/require/php)](https://packagist.org/packages/tp5er/think-auth)\n\n## 介绍\n\n许多web应用程序为用户提供了一种通过应用程序进行身份验证和“登录”的方式。在web应用程序中实现此功能可能是一项复杂且潜在风险的工作。因此，think-auth努力为您提供快速、安全、轻松地实现身份验证所需的工具。\n其核心是，think-auth的认证设施由“卫士”和“提供者”组成。防护程序定义了如何对每个请求的用户进行身份验证。例如，think-auth附带了一个会话保护程序，该程序使用会话存储和cookie来维护状态。\n提供程序定义如何从持久存储中检索用户。think-auth提供了使用Eloquent和数据库查询生成器检索用户的支持。但是，您可以根据应用程序的需要自由定义其他提供程序。\n您的应用程序的身份验证配置文件位于config/auth.php中。该文件包含几个详细记录的选项，用于调整think-auth的身份验证服务的行为。\n\n## 安装\n\n~~~\ncomposer require tp5er/think-auth\n~~~\n\n## 版本更新记录\n\n[CHANGELOG.md](https://github.com/pkg6/think-auth/blob/main/CHANGELOG.md)\n\n## 命令行\n\n~~~\n//生成基础数据结构\nphp think auth:install\n// 默认会生成 personal_access_token \u0026 user表结构\n\n//生成测试数据\nphp think seed:run\n\n//具体参考 `topthink/think-migration`\n\n\n// 使用policy类\nphp think make:policy Post\n~~~\n\n## Auth常用方法\n~~~\n//如果你愿意，除了用户的电子邮件和密码之外，还可以向身份验证查询中添加额外的查询条件。为了实现这一点，我们可以简单地将查询条件添加到传递给 attempt 方法的数组中。\nAuth::attempt(['email' =\u003e 'zhiqiang2033@gmail.com', 'password' =\u003e '123456'], true);\n\n//访问指定的看守器实例\nif (Auth::guard('admin')-\u003eattempt($credentials)) {\n    //\n}\n\n//您可以将布尔值作为第二个参数传递给 login 方法。此值指示是否需要验证会话的 「记住我」 功能。请记住，这意味着会话将被无限期地验证，或者直到用户手动注销应用程序：\nAuth::login(User::find(1), $remember = false);\n\n//只验证一次\nAuth::once(['email' =\u003e 'tp5er@qq.com', 'password' =\u003e '123456']);\n//只验证一次通过id\nAuth::onceUsingId(1);\n\n// 获取当前的认证用户信息 ...\n$user = Auth::user();\n// 获取当前的认证用户id ...\n$id = Auth::id();\n\nif (Auth::check()) {\n    // 用户已登录...\n}\n//使用户退出登录（清除会话）\nAuth::logout();\n\n//添加自定义的看守器\nAuth::extend(\"test\",function (App $app, $name, $config){\n    //返回实现Guard|StatefulGuard的对象\n\n});\n//添加自定义用户提供器\nAuth::provider(\"test\",function (App $app,$config){\n    //返回实现UserProvider的对象\n});\n\n\n//动态设置配置信息\nAuth::setConfigGuardProvider(\"admin\",\"user_table\",\"session\");\nAuth::configMergeGuards('sanctum', [\"driver\" =\u003e 'sanctum',\"provider\" =\u003e null])\nAuth::configMergeProviders(\"admin\", ['driver' =\u003e 'database','table' =\u003e \"user\"]);\n~~~\n\n## 使用policy\n\n生成Post模型\n\n~~~\nphp think make:model Post\n~~~\n\n#### 生成一个PostPolicy\n\n~~~\nphp think make:policy Post\n~~~\n\n#### 加入配置`config/auth.php`\n\n~~~\n\"policies\" =\u003e [\n    //'app\\model\\Model' =\u003e 'app\\policies\\ModelPolicy',\n    \\app\\model\\Post::class =\u003e \\app\\policies\\Post::class,\n],\n~~~\n\n## 使用\n\n~~~\nuse tp5er\\think\\auth\\access\\AuthorizesRequests\n\npublic function destroy(Post $post)\n{\n    $this-\u003eauthorize('delete', $post);\n    $post-\u003edelete();\n    return redirect('/posts');\n}\n~~~\n\n## 使用事件\n\n### 定义事件类LoginSuccessful\n\n~~~\n\u003c?php\ndeclare (strict_types = 1);\n\nnamespace app\\event;\n\nuse tp5er\\think\\auth\\events\\Login;\n\nclass LoginSuccessful\n{\n    public function handle($user $authenticated)\n    {\n        //TODO 登录成功执行\n    }\n}\n~~~\n\n### 绑定事件\n\n~~~\n'listen'    =\u003e [\n    \\tp5er\\think\\auth\\events\\Attempting::class=\u003e [\n        \\app\\event\\LoginSuccessful::class\n    ],\n    \\tp5er\\think\\auth\\events\\Authenticated::class=\u003e[],\n    \\tp5er\\think\\auth\\events\\CurrentDeviceLogout::class=\u003e[],\n    \\tp5er\\think\\auth\\events\\Failed::class=\u003e[],\n    \\tp5er\\think\\auth\\events\\Login::class=\u003e[],\n    \\tp5er\\think\\auth\\events\\Logout::class=\u003e[],\n    \\tp5er\\think\\auth\\events\\OtherDeviceLogout::class=\u003e[],\n],\n~~~\n\n### 在控制器中直接绑定事件\n\n~~~\napp()-\u003eevent-\u003elisten( Authenticated::class,function (Authenticated $user){\n    //TODO\n});\n\nAuth::loginUsingId(1);\n~~~\n\n## 在路由演示使用think-auth\n\n\u003e 根据实际需求进行开发使用\n\n在`route/app.php`添加\n\n~~~\n\\tp5er\\think\\auth\\think\\Route::api();\n~~~\n\n部分代码(此处只是部分代码,演示有可能随时发生变化,但使用方法是不会发生变化)\n\n~~~\nuse think\\facade\\Route as thinkRoute;\nuse tp5er\\think\\auth\\contracts\\Authenticatable;\nuse tp5er\\think\\auth\\facade\\Gate;\nuse tp5er\\think\\auth\\User;\n\n//定义一个演示的权限\nGate::define('edit-settings', function (Authenticatable $authenticatable) {\n    return true;\n});\n\nthinkRoute::get(\"/api/register\", function () {\n    //TODO 自己根据实际需求进行注册\n    $user = new User();\n    $user-\u003ename = \"admin\";\n    $user-\u003epassword = hash_make(\"admin\");\n    $user-\u003esave();\n\n    return json(['code' =\u003e 0, \"msge\" =\u003e $user]);\n});\n\nthinkRoute::get(\"/api/login\", function () {\n    //TODO 自己根据实际需求进行登录\n    auth()-\u003eattempt([\"name\" =\u003e \"admin\", \"password\" =\u003e \"admin\"]);\n\n    return json(['code' =\u003e 0, \"msge\" =\u003e \"登录成功\"]);\n});\nthinkRoute::get(\"/api/user\", function () {\n\n    $user = requesta()-\u003euser();\n    //$user=  auth()-\u003euser();\n\n    return json(['code' =\u003e 0, \"msg\" =\u003e \"获取登录信息\", \"data\" =\u003e $user]);\n});\n\nthinkRoute::get(\"/api/scan\", function () {\n\n    $ret = [];\n    if (Gate::allows('edit-settings')) {\n        $ret[\"edit-settings\"] = \"有权限\";\n    } else {\n        $ret[\"edit-settings\"] = \"无权限\";\n    }\n\n    if (Gate::allows('delete-settings')) {\n        $ret[\"delete-settings\"] = \"有权限\";\n    } else {\n        $ret[\"delete-settings\"] = \"无权限\";\n    }\n\n    return json(['code' =\u003e 0, \"msg\" =\u003e \"获取权限列表\", 'data' =\u003e $ret]);\n\n});\n\nthinkRoute::get(\"/api/token\", function () {\n    //$user = requesta()-\u003euser();\n    $user = auth()-\u003euser();\n    $token = $user-\u003ecreateToken(\"test-token\");\n\n    return json(['code' =\u003e 0, \"msg\" =\u003e \"获取token信息\", \"data\" =\u003e [\"token\" =\u003e $token-\u003eplainTextToken]]);\n});\n\nthinkRoute::get(\"/api/sanctum\", function () {\n    //TODO 逻辑\n    // 1. 首先判断你是否完成登录，通过默认guard中获取用户信息，如果有用户进行就直接返回\n    // 2. 如果在默认的guard没有获取到用户信息就通过header中获取Authorization，然后进行获取用户信息\n    // 3. Authorization是用`/api/token`中拿到的token，然后进字符串拼接成：（Bearer token）放在header中Bearer 参考curl\n    // curl -H \"Authorization: Bearer 9|DqTQsBngTVJcFwJkslyvdZSeGuAjgaeikknQPHBI\"  \"http://127.0.0.1:8000/api/sanctum\"\n    // 注意： 使用sanctum必须使用模型，database 无法进行access权限验证\n\n    //$user = requesta()-\u003euser();\n    $user = auth()-\u003euser();\n\n    return json(['code' =\u003e 0, \"msg\" =\u003e \"通过sanctum获取用户信息\", \"data\" =\u003e $user]);\n})-\u003emiddleware('auth', \"sanctum\");\n\nthinkRoute::get(\"/api/tokencan\", function () {\n    //$user = requesta()-\u003euser();\n    $user = auth()-\u003euser();\n    $ret = [];\n    //TODO 默认accessToken是tp5er\\think\\auth\\sanctum\\TransientToken\n    // 此处无论是什么都有权限的哦\n    // 可以使用withAccessToken(HasAbilities $accessToken) 进行自定义\n    if ($user-\u003etokenCan(\"edit-settings\")) {\n        $ret[\"tokenCan\"] = \"有权限\";\n    } else {\n        $ret[\"tokenCan\"] = \"无权限\";\n    }\n    //TODO Gate 定义的关系\n    if ($user-\u003ecan(\"edit-settings\")) {\n        $ret[\"edit-settings\"] = \"有权限\";\n    } else {\n        $ret[\"edit-settings\"] = \"无权限\";\n    }\n    if ($user-\u003ecan('delete-settings')) {\n        $ret[\"delete-settings\"] = \"有权限\";\n    } else {\n        $ret[\"delete-settings\"] = \"无权限\";\n    }\n\n    return json(['code' =\u003e 0, \"msg\" =\u003e \"获取权限列表\", 'data' =\u003e $ret]);\n\n})-\u003emiddleware('auth', \"sanctum\");\n\n//JWT 使用\nthinkRoute::get(\"/jwt/token\", function () {\n    $token = auth('jwt')-\u003eattempt([\"name\" =\u003e \"admin\", \"password\" =\u003e \"admin\"]);\n\n    return json([\n        \"code\" =\u003e 0,\n        \"msg\" =\u003e \"获取token信息\",\n        \"data\" =\u003e [\n            'access_token' =\u003e $token,\n            'token_type' =\u003e 'bearer',\n            'expires_in' =\u003e auth('jwt')-\u003efactory()-\u003egetTTL() * 60,\n            'claims' =\u003e auth('jwt')-\u003egetPayload()\n        ]\n    ]);\n});\nthinkRoute::get(\"/jwt/user\", function () {\n    $user = auth('jwt')-\u003euser();\n\n    return json([\n        \"code\" =\u003e 0,\n        \"msg\" =\u003e \"获取用户信息\",\n        \"data\" =\u003e $user\n    ]);\n})-\u003emiddleware('auth', \"jwt\");\n\nthinkRoute::get(\"/jwt/logout\", function () {\n    auth('jwt')-\u003elogout();\n\n    return json([\n        \"code\" =\u003e 0,\n        \"msg\" =\u003e \"退出登录\",\n    ]);\n})-\u003emiddleware('auth', \"jwt\");\n\nthinkRoute::get(\"/jwt/refresh\", function () {\n    $token = auth('jwt')-\u003eparseToken()-\u003egetToken()-\u003eget();\n    $newtoken = auth('jwt')-\u003eparseToken()-\u003erefresh();\n\n    return json([\n        \"code\" =\u003e 0,\n        \"msg\" =\u003e \"刷新token成功\",\n        \"data\" =\u003e [\n            \"token\" =\u003e $token,\n            'refresh_token' =\u003e $newtoken,\n            'token_type' =\u003e 'bearer',\n            'expires_in' =\u003e auth('jwt')-\u003efactory()-\u003egetTTL() * 60\n        ]\n    ]);\n\n})-\u003emiddleware('auth', \"jwt\");\n~~~\n\n## [casbin权限验证](https://casbin.org/)\n\n~~~\n// 给用户alice赋予对data1的read权限\nCasbin::addPolicy('alice', 'data1', 'read');\n//判断是权限策略是否存在\nif (Casbin::hasPolicy('alice', 'data1', 'read')){\n    $output-\u003einfo(\"alice 有权限\");\n}\n//移除权限\nCasbin::removePolicy('alice', 'data1', 'read');\n\n//使用决策器，验证权限\n$sub = 'alice'; // the user that wants to access a resource.\n$obj = 'data1'; // the resource that is going to be accessed.\n$act = 'read'; // the operation that the user performs on the resource.\nif (true === Casbin::enforce($sub, $obj, $act)) {\n    // permit alice to read data1\n    echo 'permit alice to read data1';\n} else {\n    // deny the request, show an error\n}\n~~~\n\n## [密码生成和验证](https://github.com/pkg6/think-hashing)\n\n~~~\nuse tp5er\\think\\hashing\\facade\\Hash;\n\n//加密\n$hashedValue= Hash::make(\"123456\");\n//验证密码是否有效\n$check = Hash::check(\"123456\",$hashedValue);\n\n//加密\n$hashedValue = hash_make(\"123456\");\n//验证密码是否有效\nhash_check(\"123456\",$hashedValue);\n~~~\n\n## 加入我们\n\n如果你认可我们的开源项目，有兴趣为 think-auth 的发展做贡献，竭诚欢迎加入我们一起开发完善。无论是[报告错误](https://github.com/pkg6/think-auth/issues)或是 [Pull Request](https://github.com/pkg6/think-hashing/pulls) 开发，那怕是修改一个错别字也是对我们莫大的帮助。\n\n## 感谢\n\nhttps://laravel.com/docs/8.x/authentication\n\nhttps://github.com/laravel/framework/tree/8.x/src/Illuminate/Auth\n\nhttps://github.com/laravel/sanctum\n\nhttps://github.com/tymondesigns/jwt-auth\n\nhttps://github.com/php-casbin/think-casbin\n\n## 许可协议\n\n[MIT](https://opensource.org/licenses/MIT)\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpkg6%2Fthink-auth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpkg6%2Fthink-auth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpkg6%2Fthink-auth/lists"}