定制 loadsys/cakephp-stateless-auth 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

loadsys/cakephp-stateless-auth

Composer 安装命令:

composer require loadsys/cakephp-stateless-auth

包简介

A replacement CakePHP Authentication/Authorization Component that is fully and strictly stateless. Designed to be used with Cake apps that are only accessed RESTfully.

README 文档

README

Latest Version Software License Build Status Coverage Status Total Downloads

A replacement CakePHP Authentication/Authorization Component that is fully and strictly stateless. Designed to be used with Cake apps that are only accessed RESTfully.

The provided component is intended to replace Cake's stock AuthCompnent. This replacement StatelessAuthComponent is a stripped down and simplified version that by default looks for an Authorization header in the HTTP request and populates Auth->User() using the Bearer [token] value from that header. (This is instead of the stock AuthComponent's default operation of looking up data from an active $_SESSION on repeat connections using the cookie provided by the browser.) It supports plug-able Authenticate and Authorize objects, and the package includes a few that may be of use.

⚠️ This is still unstable software and probably not suitable for public use yet.

Requirements

  • PHP >= 5.4.0
  • CakePHP >= 2.6

Installation

Composer

  • Run this shell command
$ composer require loadsys/cakephp-stateless-auth:dev-master

Setup

Load the plugin and be sure that bootstrap is set to true:

// Config/boostrap.php
CakePlugin::load('StatelessAuth', array('bootstrap' => true));
// or
CakePlugin::loadAll(array(
	'StatelessAuth' => array('bootstrap' => true),
));

The CakePHP book has more information on doing REST APIs with CakePHP and this feature.

Sample Usage

In your project's AppController, change your $components array to use this plugin's StatelessAuthComponent, but alias it to allow access by the common name:

	public $components = array(
		'Auth' => array(
			'className' => 'StatelessAuth.StatelessAuth',
			'authenticate' => array(
				'className' => 'StatelessAuth.Token',

				// Additional examples:

				// 'userModel' => 'User',
				// 'tokenField' => 'token',
				// 'recursive' => -1,
				// 'contain' => array('Permission'),
				// 'conditions' => array('User.is_active' => true),
				// 'passwordHasher' => 'Blowfish',
			),
		),
		'Paginator',
		'DebugKit.Toolbar',
	);

How you authenticate your requests to your Cake app is up to you. If you use the bundled TokenAuthenticate object as demonstrated above, you must include an Authorization header in your request that includes a Bearer [token] that matches a valid token in your User table. The token represents the User's login session, in effect replacing $_SESSION. A sample HTTP request might look like the following:

GET /users/view HTTP/1.1
Host: vagrant.dev:80
Authorization: Bearer 0193d044dd2034bfdeb1ffa33c5fff9b

⚠️ Just like normal Auth, the token will be sent in the clear and could be intercepted and re-used, so be sure to secure your connections using SSL.

TokenAuthenticate will attempt to look up a User record using the provided token. You can define the name of your User model to query and the name of the token field to check in the component configuration as shown above.

The StatelessAuthComponent uses this authenticate object by default.

You will still access the Component as usual In your controllers:

	/**
	 * Allow the logged-in User to view their own record.
	 *
	 * @return void
	 * @throws NotFoundException If the passed id record does not exist
	 */
	public function view() {
		$id = $this->Auth->user('id'); // <-- Populated by the stateless auth component.
		if (!$id) {
			throw new NotFoundException(__('Please log in to view your User record.'));
		}
		$options = array(
			'conditions' => array(
				'User.' . $this->User->primaryKey => $id,
			),
		);
		$user = $this->User->find('first', $options);
		$this->set(compact('user'));
	}

You must define an ::isAuthorized($user) method either in each controller or your AppController that returns true or false based on whether the current Auth->user() should be allowed to access the current controller action.

If you wish for all authenticated Users to have access to all methods, you can place the following in your project's AppController:

	public function isAuthorized($user) {
		return true;
	}

Alternatively, you can supply your own authorization object to perform the appropriate checks yourself. See Cake's cookbook section on Authorization for details.

Error and Exception Handling Setup

Errors and Exceptions are handled via a separate CakePHP plugin, included via Composer: SerializersErrors

Please read the documentation there for more information on the specifics.

Modify your app/Config/core.php file to use the Custom Exceptions/Error handling in SerializersErrors.

Configure::write('Exception', array(
	'handler' => 'ErrorHandler::handleException',
	'renderer' => 'SerializersErrors.SerializerExceptionRenderer',
	'log' => true,
));

This does two things:

  • Errors and Exceptions get output as correctly formatted JSON API, JSON or HTML depending on the request type
  • Allows the use of Custom Exceptions that match Ember Data exceptions for error cases
  • The classes in this plugin use this format to enable easier use for API Authentication Handling

Swapping authentication and authorization objects

The project comes with additional Auth objects that can be used to extend the functionality surrounding HTTP header authentication. The TokenLoginLogoutAuthenticate object, for example, allows you to hook callback behavior into the Auth->login() and Auth->logout() processes to perform additional Model operations.

See Controller/Component/Auth/TokenLoginLogoutAuthenticate.php, specifically ::requireUserModelMethods() for details and expected method signatures.

@TODO: Write up proper documentation on the callback methods needed.

Contributing

Reporting Issues

Please use GitHub Isuses for listing any known defects or issues.

Development

When developing this plugin, please fork and issue a PR for any new development.

The Complete Test Suite for the Plugin can be run via this command:

./lib/Cake/Console/cake test StatelessAuth AllStatelessAuth

License

MIT

Copyright

Loadsys Web Strategies 2015

loadsys/cakephp-stateless-auth 适用场景与选型建议

loadsys/cakephp-stateless-auth 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 371 次下载、GitHub Stars 达 7, 最近一次更新时间为 2015 年 04 月 10 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 loadsys/cakephp-stateless-auth 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 371
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 7
  • 点击次数: 29
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 7
  • Watchers: 7
  • Forks: 4
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2015-04-10