lahaxearnaud/laravel-token
最新稳定版本:v0.5.1
Composer 安装命令:
composer require lahaxearnaud/laravel-token
包简介
Laravel 4 token management
关键字:
README 文档
README
Table of Contents
Installation
{
"require": {
"lahaxearnaud/laravel-token": "~0.5"
}
}
Database
$ php artisan migrate --package="lahaxearnaud/laravel-token"
Provider
'providers' => array( // ... 'Lahaxearnaud\LaravelToken\LaravelTokenServiceProvider', ),
Facade
'aliases' => array( // ... 'Token' => 'Lahaxearnaud\LaravelToken\LaravelTokenFacade', ),
Usage
Create token
$token = Token::create($userID, $allowLogin);
If $allowLogin is set to true the token can be use to authentification via route filter.
Crypt token
$token = Token::create($userID, $allowLogin); $cryptToken = Token::cryptToken($token->token);
If $allowLogin is set to true the token can be use to authentification via route filter.
Validate token
If you crypt your token
$tokenStr = Token::getTokenValueFromRequest(); $cryptToken = Token::isValidCryptToken($token->token, $userId);
If you don't crypt your token:
$tokenStr = Token::getTokenValueFromRequest(); $cryptToken = Token::isValidToken($token->token, $userId);
If you use those functions the token is not burn. It can be use many times.
For one shot usage token:
$tokenStr = Token::getTokenValueFromRequest(); /** * if the token is crypt do : * $tokenStr = Token::uncryptToken($tokenStr); **/ $tokenValid = true; try { // find the token $token = $token->findByToken($tokenStr, $userId); // test the token validity if (Token::isValidToken($token)) { // do what you need to do // delete the token Token::burn($token); } else { $tokenValid = false; } } catch (TokenNotFoundException $e) { $tokenValid = false; } if($tokenValid) { // manage errors }
Route filter
Simple token protection:
Route::get('/token-protected', array('before' => 'token', function () { echo "I am token protected"; }));
Authentification by token:
The token used for an authentification must be a login token, pleaserefer to the token creation section
Route::get('/login-by-token', array('before' => 'token.auth', function () { echo Auth::user()->username; }));
In order to use the authentification by token your class User need to implements Lahaxearnaud\LaravelToken\Models\UserTokenInterface
use Illuminate\Auth\UserTrait; use Illuminate\Auth\UserInterface; use Illuminate\Auth\Reminders\RemindableTrait; use Illuminate\Auth\Reminders\RemindableInterface; use Lahaxearnaud\LaravelToken\Models\UserTokenInterface; class User extends Eloquent implements UserInterface, RemindableInterface, UserTokenInterface { use UserTrait, RemindableTrait; /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = array('password', 'remember_token'); public function loggableByToken() { return true; } }
The method loggableByToken is called when a user try to authentificate with a token.
If an error occur on token validation a TokenExeption is throw, please go to Exceptions section.
By default you can send your token in parameter or header. The default name of the field is token but you
can change it by publishing and change the configuration:
$ php artisan config:publish lahaxearnaud/laravel-token
Then change the tokenFieldName config/packages/lahaxearnaud/laravel-token/config.php.
You can get the token instance via:
Token::getCurrentToken();
Exceptions
If you use route filter you need to handle some Exceptions. Add the following error handler in you filter.php to catch them.
This is basic example, change the behavior to fit your needs (redirect, log...).
App::error(function(\Lahaxearnaud\LaravelToken\exeptions\TokenException $exception) { if($exception instanceof \Lahaxearnaud\LaravelToken\exeptions\TokenNotFoundException) { return \Response::make('Unauthorized (Not found)', 401); } if($exception instanceof \Lahaxearnaud\LaravelToken\exeptions\TokenNotValidException) { return \Response::make('Unauthorized (Not valid token)', 401); } if($exception instanceof \Lahaxearnaud\LaravelToken\exeptions\UserNotLoggableByTokenException) { return \Response::make('Unauthorized (Not loggable by token)', 401); } if($exception instanceof \Lahaxearnaud\LaravelToken\exeptions\NotLoginTokenException) { return \Response::make('Unauthorized (Not login token)', 401); } });
Events
You can listen events:
- Token not found
- name:
token.notFound - parameters:
- the token string
- name:
- Token not valid
- name:
token.notValid - parameters:
- the token object
- name:
- Token doesn't allow to be used for login
- name:
token.notLoginToken - parameters:
- the token object
- name:
- The user can't logged with a token
- name:
token.notLoggableUser - parameters:
- the token object
- the user object
- name:
- Token burn
- name:
token.burned - parameters:
- the token object
- name:
- Token created
- name:
token.created - parameters:
- the token object
- name:
- Token saved
- name:
token.saved - parameters:
- the token object
- name:
Commands
A new artisan command is added to your project in order to help you to clean your token table
### Delete expired tokens
Without any option the command delete all expired tokens.
```bash
$ php artisan token:clean
```
### Truncate the table
If you specified ``--all`` all token will be deleted
```bash
$ php artisan token:clean -all
```
API
Security
Crypt a string token in order to get a public token
Token::cryptToken ($uncrypt)
Uncrypt a public token in order to get the private token
Token::uncryptToken ($crypt)
Creation
Create a Token instance (directly saved in database)
Token::create ($userId, $allowLogin = false, $lifetime = 3600, $length = 100)
If $allowLogin is set to true the token can be use to authentification via route filter.
Deletion
Delete the token
Token::burn (Token $token)
Validation
Fetch the token, check id the token has the good user ID and if it is not expired
Token::isValidToken ($token, $userId)
Same as isValidToken but uncrypt the token before trying to find him
Token::isValidCryptToken ($token, $userId)
Only validate if the token is expired
Token::isValid (Token $token)
Find
Find the token by ID
Token::find ($id)
Find the token by token string
Token::findByToken ($token, $userId)
Find all token for an user
Token::findByUser ($idUser)
Todo
- config to allow only one token by user and type
lahaxearnaud/laravel-token 适用场景与选型建议
lahaxearnaud/laravel-token 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 395 次下载、GitHub Stars 达 10, 最近一次更新时间为 2014 年 12 月 23 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「notification」 「laravel」 「token」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 lahaxearnaud/laravel-token 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 lahaxearnaud/laravel-token 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 lahaxearnaud/laravel-token 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
This package makes it easy to send notifications via AfricasTalking with Laravel
A package for validating Google Cloud's JWT provided by webhooks
JSON Web Token Authentication for Laravel and Lumen
Apple Push Notification & Feedback Provider
Throttle notifications on a per-channel basis
JSON Web Token Authentication for Laravel and Lumen
统计信息
- 总下载量: 395
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 11
- 点击次数: 17
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2014-12-23