glauberkyves / phalcon-jwt-auth
此包的最新版本(v1.0.2)没有可用的许可证信息。
Phalcon Micro的一个简单的JWT中间件,用于处理无状态认证
v1.0.2
2020-03-01 16:06 UTC
Requires
- php: >=7.0
- ext-phalcon: ^4.0
- firebase/php-jwt: ^5.0
This package is not auto-updated.
Last update: 2024-09-24 13:51:29 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"服务来访问中间件。
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库。要了解更多信息,请访问: 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)