phpixie/auth
Composer 安装命令:
composer require phpixie/auth
包简介
Auth library for PHPixie
关键字:
README 文档
README
PHPixie Authentication library
This is the base package of the PHPixie authentication subsystem, which is split into several components. This manual covers all of them for.
Authentication is the most critical part of any application, implementing it the right way is hard, and any errors can compromise a lot of user, especially in opensource projects. Using old hash functions, cryptographically unsecure random generators and the misues of cookies are sadly things we still encounter frequently. This is why I spent a lot of time to carefully implement authentication in PHPixie.
What makes it secure
- Using the secure password_hash() in PHP 5.5 and a compatibilty package for older PHP versions
- Same for the crryptographically secure random_bytes() from PHP 7
- Following the best practices for persisted login
The last point is the most interesting and currently no other framework supports it out of the box. The idea behind it lies in the use of a special table for storing auth tokens.
- When a user first logs in a random series identiefier and a passphrase are generated. These are then sent to the user as a cookie.
- The series and passphrase are hashed, and then the series, the resulting hash, user id and expiration date are saved in the database
- When a user enters the site (and the session is not already present) his cookie is rehashed and compared to the hash in the database. If those match, the user is logged in, a session is started and a new token is generated for the user.
- If the hashes don't match a theft is assumed and any token with the same series identifier is deleted from the table
This approach has huge benefits when compared to the usual approach of storing a single token in the users table:
- Users can have multiple persistent session on multiple devices (each device will get its own series)
- Tokens are of one time use, and if stolen using a MITM attack cannot be reused.
- Tokens cannot be bruteforced, since the first unsuccessful attempt removes the series
- If a database is ever compromised, only token hashes are exposed, so the attacker still cannot login.
And basically if your framework is storing the paristent token as-is in the database without hashing it, it is comparable to storing an unhashed password there. And there are still a lot of popular frameworks doing this, just take a look.
Initializing
The initialization might seem a bit overwhelming, but that is because the architecture is highly modular and tries to minimize any unneeded dependencies. If you don't need a particular extension, feel free to not build it. Of course if you are using the PHPixie framework all of this is handled automatically.
$slice = new \PHPixie\Slice(); // The database component is only required if you need // the token storage functionality $database = new \PHPixie\Database($slice->arrayData(array( 'default' => array( 'driver' => 'pdo', 'connection' => 'sqlite::memory:' ) ))); // the security component handles hashing, random numbers and tokens $security = new \PHPixie\Security($database); // This plugin allows using the login/password auth $authLogin = new \PHPixie\AuthLogin($security); // To use HTTP authorization we must first // build an HTTP context $http = new \PHPixie\HTTP(); $request = $http->request(); $context = $http->context($request); $contextContainer = $http->contextContainer($context); $authHttp = new \PHPixie\AuthHTTP($security, $contextContainer); $authConfig = $slice->arrayData(array( // config options )); // This is your class that must impplement the // \PHPixie\Auth\Repositories\Registry interface $authRepositories = new AuthRepositories(); // Initialize the Auth system with both extensions $auth = new \PHPixie\Auth($authConfig, $authRepositories, array( $authLogin->providers(), $authHttp->providers() ));
Repositories
The first thing you need is a user repository. The most basic one is PHPixie\Auth\Repositories\Repository which only provides fetching users
by their id. But for any practical use you will probably need the \PHPixie\AuthLogin\Repository interface, which allows for the password based
login. You will need a repostory builder to pass to the Auth component:
class AuthRepositories extends \PHPixie\Auth\Repositories\Registry\Builder { protected function buildUserRepository() { return new YourRepository(); } } // that is the second parameter we passed to Auth $authRepositories = new AuthRepositories();
Framework support
If you are using the PHPixie ORM all you need is to extend the premade wrappers:
namespace Project\App\ORMWrappers\User; // Repository wrapper class Repository extends \PHPixie\AuthORM\Repositories\Type\Login { // You can supply multiple login fields, // in this case its both usernam and email protected function loginFields() { return array('username', 'email'); } }
namespace Project\App\ORMWrappers\User; // Entity wrapper class Entity extends \PHPixie\AuthORM\Repositories\Type\Login\User { // get hashed password value // from the field in the database public function passwordHash() { return $this->passwordHash; } }
Don't forget to register these wrappers with the ORM:
namespace Project\App; class ORMWrappers extends \PHPixie\ORM\Wrappers\Implementation { protected $databaseEntities = array('user'); protected $databaseRepositories = array('user'); public function userEntity($entity) { return new ORMWrappers\User\Entity($entity); } public function userRepository($repository) { return new ORMWrappers\User\Repository($repository); } }
And register an AuthRepositories class in your bundle
namespace Project\App; class AuthRepositories extends \PHPixie\Auth\Repositories\Registry\Builder { protected $builder; public function __construct($builder) { $this->builder = $builder; } protected function buildUserRepository() { $orm = $this->builder->components()->orm(); return $orm->repository('user'); } }
namespace Project\App; class Builder extends \PHPixie\DefaultBundle\Builder { protected function buildAuthRepositories() { return new AuthRepositories($this); } }
Configuration options
The configuration is split into domains. A domain is a context that consists of a repository and authentication providers. Usually your app will have only a single domain, but sometimes you may need more. E.g. imagine you have some sort of the social login for site users, but site administrators are logged in on a separate page using their database accounts.
// /assets/auth.php return array( 'domains' => array( 'default' => array( // using the 'user' repository from the 'app' bundle 'repository' => 'app.user', 'providers' => array( // include session support 'session' => array( 'type' => 'http.session' ), // include persistent cookies (remember me) 'cookie' => array( 'type' => 'http.cookie', // when a cookie is used to login // persist login using session too 'persistProviders' => array('session'), // token storage 'tokens' => array( 'storage' => array( 'type' => 'database', 'table' => 'tokens', 'defaultLifetime' => 3600*24*14 // two weeks ) ) ), // password login suport 'password' => array( 'type' => 'login.password', // remember the user in session // note that we did not add 'cookies' to this array // because we don't want every login to be persistent 'persistProviders' => array('session') ) ) ) );
As you can see all providers are entirely independent of each other, whcih means we can alter the behavior easily. For example let's assume that we don't want to use sessions at all, just the cookie based login, and turn off token regeneration on each request:
// /assets/auth.php return array( 'domains' => array( 'default' => array( 'cookie' => array( 'type' => 'http.cookie', // token storage 'tokens' => array( 'storage' => array( 'type' => 'database', 'table' => 'tokens', 'defaultLifetime' => 3600*24*14, // don't refresh tokens 'refresh' => false ) ) ), 'password' => array( 'type' => 'login.password', // persist lgoin with cookie 'persistProviders' => array('cookie') ) ) ) );
Token storage
In both examples we referenced a database table used to store tokens. In fact this can also be a MongoDB collection. The SQL for the table creation would be as follows:
CREATE TABLE `tokens` ( `series` varchar(50) NOT NULL, `userId` int(11) DEFAULT NULL, `challenge` varchar(50) DEFAULT NULL, `expires` bigint(20) DEFAULT NULL, PRIMARY KEY (`series`) );
Usage example
Now that we have everything configured, lets test how it all works together. Here is a simple processor:
namespace Project\App\HTTPProcessors; class Auth extends \PHPixie\DefaultBundle\Processor\HTTP\Actions { protected $builder; public function __construct($builder) { $this->builder = $builder; } // Check if the user is logged in public function defaultAction($request) { $user = $this->domain()->user(); return $user ? $user->username : 'not logged'; } // Action for adding user to the database public function addAction($request) { $query = $request->query(); $username = $query->get('username'); $password = $query->get('password'); $orm = $this->builder->components()->orm(); $provider = $this->domain()->provider('password'); $user = $orm->createEntity('user'); $user->username = $username; // Hash password using the password provider $user->passwordHash = $provider->hash($password); $user->save(); return 'added'; } // Attempt to login user using his password public function loginAction($request) { $query = $request->query(); $username = $query->get('username'); $password = $query->get('password'); $provider = $this->domain()->provider('password'); $user = $provider->login($username, $password); if($user) { // Generate persistent login cookie $provider = $this->domain()->provider('cookie'); $provider->persist(); } return $user ? 'success' : 'wrong password'; } // logout action public function logoutAction($request) { $this->domain()->forgetUser(); return 'logged out'; } protected function domain() { $auth = $this->builder->components()->auth(); return $auth->domain(); } }
To test it try hitting these URLs:
- /auth - user is not logged in
- /auth/add?username=dracony&password=5 - add user to the database
- /auth/login?username=dracony&password=5 - log in
- /auth - check login
- /auth/logout - logout
Adding your own providers
At some point you will probably need to add your own login providers (e.g. for social networks), to do that you need to satisfy a PHPixie\Auth\Providers\Builder interface and pass it along with the other extensions. Try looking at the AuthLogin component for an example. If you are using the PHPixie Framework
you can pass your custom extensions to the Auth component by overloading this method.
phpixie/auth 适用场景与选型建议
phpixie/auth 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 23.15k 次下载、GitHub Stars 达 3, 最近一次更新时间为 2013 年 04 月 26 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「auth」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 phpixie/auth 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 phpixie/auth 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 phpixie/auth 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Laravel Multiauth package
A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.
This package provides a flexible way to add Role-based Permissions to Laravel 6.x
Email Toolkit Plugin for CakePHP
:Small library PHP for authentication support facebook, google, key, jwt, diggest, basic and session
RESTful API server for structured and self-documenting resources over JSON, XML, ...
统计信息
- 总下载量: 23.15k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 3
- 点击次数: 10
- 依赖项目数: 6
- 推荐数: 0
其他信息
- 授权协议: BSD-3-Clause
- 更新时间: 2013-04-26