承接 dmkit/phalcon-jwt-auth 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

dmkit/phalcon-jwt-auth

Composer 安装命令:

composer require dmkit/phalcon-jwt-auth

包简介

A simple JWT middleware for Phalcon Micro to handle stateless authentication

README 文档

README

A simple JWT middleware for Phalcon Micro to handle stateless authentication.

Installation

$ composer require dmkit/phalcon-jwt-auth

or in your composer.json

{
    "require": {
		"dmkit/phalcon-jwt-auth" : "dev-master"
    }
}

then run

$ composer update

Usage

Configuration - Loading the config service

in config.ini or in any config file

[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

in bootstrap or index file

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();

Configuration - Don't want to use a config file? then pass the config instead

in bootstrap or index file

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();

Authentication

To make authenticated requests via http, you will need to set an authorization headers as follows:

Authorization: Bearer {yourtokenhere}

or pass the token as a query string

?_token={yourtokenhere}

Callbacks

By default if the authentication fails, the middleware will stop the execution of routes and will immediately return a response of 401 Unauthorized. If you want to add your own handler:

$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;
});

If you want an additional checking on the authentication, like intentionally expiring a token based on the payload issued date, you may do so:

$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;
 }

});

The Auth service

You can access the middleware by calling the "auth" service.

print_r( $app['auth']->data() );

print_r( $app->getDI()->get('auth')->data('email') );

// in your contoller
print_r( $this->auth->data() );

If you want to change the service name:

AuthMicro::$diName = 'jwtAuth';

Creating a token

In your controller or route handler

$payload = [
    'sub'   => $user->id,
    'email' => $user->email,
    'username' =>  $user->username,
    'role'  => 'admin',
    'iat' => time(),
];
$token = $this->auth->make($payload);

Accessing the authenticated user / data

In your controller or route handler

echo $this->auth->id(); // will look for sub or id payload

echo $this->auth->data(); // return all payload

echo $this->auth->data('email');

Extending

If you want to add your own middleware or play around:

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 uses the Firebase JWT library. To learn more about it and JSON Web Tokens in general, visit: https://github.com/firebase/php-jwt https://jwt.io/introduction/

Tests

Install 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)

dmkit/phalcon-jwt-auth 适用场景与选型建议

dmkit/phalcon-jwt-auth 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 42.74k 次下载、GitHub Stars 达 35, 最近一次更新时间为 2016 年 12 月 05 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「Authentication」 「jwt」 「phalcon」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 dmkit/phalcon-jwt-auth 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 dmkit/phalcon-jwt-auth 我们能提供哪些服务?
定制开发 / 二次开发

基于 dmkit/phalcon-jwt-auth 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 42.74k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 37
  • 点击次数: 22
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 35
  • Watchers: 3
  • Forks: 22
  • 开发语言: PHP

其他信息

  • 授权协议: Unknown
  • 更新时间: 2016-12-05