fherryfherry/laravel-api-token
Composer 安装命令:
composer require fherryfherry/laravel-api-token
包简介
Make a tokenize for our API in Laravel is never been easy
README 文档
README
This library is to Tokenize your current API Restful very easy. It makes your API more secure.
How this library works :
- It will create table
laravel_api_tokens - Insert the token data into it
- Validate user request with table
laravel_api_tokens
Requirements
- Laravel 6, 7, or 8
- PHP 7.4 or 8.x
Installation
Run this command on your root project
composer require fherryfherry/laravel-api-token
Run the migration bellow
php artisan migrate
After installation is done, then run bellow command to export configuration file :
php artisan vendor:publish --provider=FherryFherry\LaravelApiToken\LaravelSimpleApiTokenServiceProvider
Configuration
<?php return [ "expiry_unit"=> "day", // day, hour, minute "expiry_duration" => 3, // expiry duration by unit "token_length"=> 128, // how long token is // VALIDATION LEVEL ============================================ // // Level 1 = Validate by token only (default) // // Level 2 = Validate by token and ip address // // Level 3 = Validate by token, ip address and user agent // // // // Please be careful with validation 2 and 3 because ip address // // can suddenly change. Usually this because user providers // // ============================================================= // "validation_level"=> 1, "basic_auth_user" => env("BASIC_AUTH_USER"), // user to request token "basic_auth_pass" => env("BASIC_AUTH_PASS") // password to request token ];
Setting .ENV
Open the .env file, and paste these bellow on the bottom of file
BASIC_AUTH_USER="example" BASIC_AUTH_PASS="123456"
You could change its value.
Save User Data Into Token
You should create your own Login API. Then after the login is succeeded you could call this helper. For the first, add these bellow to top of the class
use FherryFherry\LaravelApiToken\Helper\LaravelSimpleApiToken;
Then in your login method would be like these
public function postLogin(Request $request) { // ... if(Auth::attempt($request->except("_token"))) { // Then after that call this helper LaravelSimpleApiToken::saveLoginData($request, $user->id, $user->name); // Or if you have a role LaravelSimpleApiToken::saveLoginData($request, $user->id, $user->name, $user->role); } // ... }
Request Token Endpoint
Give this endpoint to your frontend engineer. (I assume you use artisan serve, instead adjust the base domain)
http://localhost:8080/api/auth/request-token
Add header parameter with Basic Authorization.
How to use Basic Authorization you could refer this document. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization
This API will produce like these bellow :
{
"status": 1,
"message": "success",
"data": {
"expired_at": "2013-05-05T16:34:42+00:00",
"access_token": "bG9yZW0gaXBzdW0=",
"refresh_token": "bG9yZW0gaXBzdW0="
}
}
Frontend engineer should save the expired_at,access_token,refresh_token value.
Refresh Token Endpoint
This API is to extend the expired time of access_token without request token again. But you will get new access_token,refresh_token,expired_at.
The difference with Request Token is you don't need to hit the Login API again.
http://localhost:8080/api/auth/refresh-token
Frontend engineer need to add a Header Parameter with Bearer Authorization
Authorization: Bearer {access_token}
This API will produce like these bellow :
{
"status": 1,
"message": "success",
"data": {
"expired_at": "2013-05-05T16:34:42+00:00",
"access_token": "bG9yZW0gaXBzdW0=",
"refresh_token": "bG9yZW0gaXBzdW0="
}
}
Frontend engineer should save the expired_at,access_token,refresh_token value. For next header authorization.
Secure Your API With Token
To prevent any user hit your API Without token, so you have to add laravel_api_token middleware to your API Route.
Open your API route location (I assume you use routes/api.php)
Route::middleware(['api','laravel_api_token'])->group(function() { // place your all api routes here // ... });
Frontend engineer need to add a Header Parameter with Bearer Authorization
Authorization: Bearer {access_token}
Get Current User ID
If you would like to get the current user ID, you only need to call this helper
$currentUserID = LaravelSimpleApiToken::getUserId();
Get Current User Name
If you would like to get the current user name, you only need to call this helper
$currentUserName = LaravelSimpleApiToken::getUserName();
Get Current User Role
If you would like to get the current user role, you only need to call this helper
$currentUserRole = LaravelSimpleApiToken::getUserRole();
Get Token Data
For whatever reason sometime you want to see all available column values of current token, you could call this helper
$tokenData = LaravelSimpleApiToken::getTokenData();
Destroy Token
If the user is logging out, you have to call this helper into your logout method at the bottom line is fine. So the frontend is should call the request token API again.
LaravelSimpleApiToken::destroy($request);
Support & Donation
Hi thanks for using my open source project, you could support me via : https://saweria.co/ferryariawan or via https://buymeacoffee.com/ferryariawan
Security Issue
If you found any security issue please contact me at ferdevelop15[at]gmail.com
fherryfherry/laravel-api-token 适用场景与选型建议
fherryfherry/laravel-api-token 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 16 次下载、GitHub Stars 达 0, 最近一次更新时间为 2021 年 08 月 27 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「api」 「Authentication」 「laravel」 「token」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 fherryfherry/laravel-api-token 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 fherryfherry/laravel-api-token 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 fherryfherry/laravel-api-token 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Automatically logs-in users if they are already authenticated by a remote source. (e.g. environment variable REMOTE_USER)
GraphQL authentication for your headless Craft CMS applications.
Laravel middleware to restrict a site or specific routes using HTTP basic authentication
A PSR-7 compatible library for making CRUD API endpoints
Email Toolkit Plugin for CakePHP
A list of dangerous usernames
统计信息
- 总下载量: 16
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 6
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-08-27