dmkit / phalcon-jwt-auth
此包最新版本(1.0.0)没有可用的许可证信息。
Phalcon Micro 的简单 JWT 中间件,用于处理无状态认证
1.0.0
2018-02-08 11:49 UTC
Requires
- php: >=7.0
- ext-phalcon: ^3.0
- firebase/php-jwt: ^5.0
This package is auto-updated.
Last update: 2024-09-26 05:23:04 UTC
README
Phalcon Micro 的简单 JWT 中间件,用于处理无状态认证。
安装
$ composer require dmkit/phalcon-jwt-auth
或者在您的 composer.json 中
{ "require": { "dmkit/phalcon-jwt-auth" : "dev-master" } }
然后运行
$ composer update
用法
配置 - 加载配置服务
在 config.ini 或任何配置文件中
[jwtAuth] ; JWT Secret Key secretKey = 923753F2317FC1EE5B52DF23951B ; JWT default Payload ;; expiry time in minutes payload[exp] = 1440 payload[iss] = phalcon-jwt-auth ; Micro Applications do not have a controller or dispatcher ; so to know the resource being called we have to check the actual URL. ; If you want to disable the middleware on certain routes or resource: ;; index ignoreUri[] = / ;; regex pattern with http methods ignoreUri[] = regex:/application/ ignoreUri[] = regex:/users/:POST,PUT ;; literal strings ignoreUri[] = /auth/user:POST,PUT ignoreUri[] = /auth/application
在 bootstrap 或 index 文件中
use Phalcon\Mvc\Micro; use Phalcon\Config\Adapter\Ini as ConfigIni; use Phalcon\Di\FactoryDefault; use Dmkit\Phalcon\Auth\Middleware\Micro as AuthMicro; // set default services $di = new FactoryDefault(); /** * IMPORTANT: * You must set "config" service that will load the configuration file. */ $config = new ConfigIni( APP_PATH . "app/config/config.ini"); $di->set( "config", function () use($config) { return $config; } ); $app = new Micro($di); // AUTH MICRO $auth = new AuthMicro($app); $app->handle();
配置 - 不想使用配置文件?那么传递配置
在 bootstrap 或 index 文件中
use Phalcon\Mvc\Micro; use Phalcon\Config\Adapter\Ini as ConfigIni; use Phalcon\Di\FactoryDefault; use Dmkit\Phalcon\Auth\Middleware\Micro as AuthMicro; // set default services $di = new FactoryDefault(); $app = new Micro($di); // SETUP THE CONFIG $authConfig = [ 'secretKey' => '923753F2317FC1EE5B52DF23951B1', 'payload' => [ 'exp' => 1440, 'iss' => 'phalcon-jwt-auth' ], 'ignoreUri' => [ '/', 'regex:/application/', 'regex:/users/:POST,PUT', '/auth/user:POST,PUT', '/auth/application' ] ]; // AUTH MICRO $auth = new AuthMicro($app, $authConfig); $app->handle();
认证
要通过 http 发送认证请求,您需要设置以下授权头
Authorization: Bearer {yourtokenhere}
或通过查询字符串传递令牌
?_token={yourtokenhere}
回调
默认情况下,如果认证失败,中间件将停止执行路由,并立即返回 401 未授权的响应。如果您想添加自己的处理器
$auth->onUnauthorized(function($authMicro, $app) { $response = $app["response"]; $response->setStatusCode(401, 'Unauthorized'); $response->setContentType("application/json"); // to get the error messages $response->setContent(json_encode([$authMicro->getMessages()[0]])); $response->send(); // return false to stop the execution return false; });
如果您想对认证进行额外的检查,例如根据令牌的发布日期有意使令牌过期,您可以这样操作
$auth->onCheck(function($auth) { // to get the payload $data = $auth->data(); if($data['iat'] <= strtotime('-1 day')) ) { // return false to invalidate the authentication return false; } });
Auth 服务
您可以通过调用 "auth" 服务来访问中间件。
print_r( $app['auth']->data() ); print_r( $app->getDI()->get('auth')->data('email') ); // in your contoller print_r( $this->auth->data() );
如果您想更改服务名称
AuthMicro::$diName = 'jwtAuth';
创建令牌
在您的控制器或路由处理程序中
$payload = [ 'sub' => $user->id, 'email' => $user->email, 'username' => $user->username, 'role' => 'admin', 'iat' => time(), ]; $token = $this->auth->make($payload);
访问已认证的用户/数据
在您的控制器或路由处理程序中
echo $this->auth->id(); // will look for sub or id payload echo $this->auth->data(); // return all payload echo $this->auth->data('email');
扩展
如果您想添加自己的中间件或进行实验
Dmkit\Phalcon\Auth\Auth.php and its adapters - does all the authentication Dmkit\Phalcon\Auth\TokenGetter\TokenGetter.php and its adapters - does the parsing or getting of token
JWT
Phalcon JWT Auth 使用 Firebase JWT 库。要了解更多关于它和 JSON Web Tokens 的一般信息,请访问:https://github.com/firebase/php-jwt https://jwt.net.cn/introduction/
测试
安装 PHPUnit https://phpunit.de/getting-started.html
$ phpunit --configuration phpunit.xml.dist PHPUnit 5.6.5 by Sebastian Bergmann and contributors. ......["missing token"].["members option"].["members put"].["members put"].["Expired token"].["members post"].... 15 / 15 (100%) Time: 73 ms, Memory: 10.00MB OK (15 tests, 27 assertions)