以下由laravel教學專欄為大家介紹laravel8中dingo與jwt鑑權,希望對需要的朋友有幫助!
1 什麼是dingo
dingo api包是給laravel和lumen提供的Restful的工具包,它可以與jwt組件一起配合快速的完成用戶認證,同時對於數據和運行過程中所產生的異常能夠捕捉到並且可以做出對應的響應。
主要功能:
- Router Version 路由版本管理
- http Exception 例外處理
- response transform 轉換回應格式
# 1 安裝dingo
在laravel根目錄下透過composer進行dingo擴充包的安裝,具體命令如下:
composer require dingo/api
使用以下命令可以發布API 的設定檔到config 檔案下:
php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"
2 設定dingo
關於dingo的api設定信,我們可以在.env檔案中進行設定
# dingo # API_SUBTYPE —— 项目的简称; API_SUBTYPE=lms # API_PREFIX —— 与 API_DOMAIN 二选一,路由的前缀,例如设置为 api API_PREFIX=api # 定义版本 API_VERSION=v1 # 是否开启调试模式 API_DEBUG=true
關於dingo的詳細設定請查看相關文件:https:/ /learnku.com/docs/dingo-api/2.0.0/Configuration/1444
2 什麼是JWT
jwt全名為JSON Web Tokens ,是一個非常輕巧的規範,這個規範允許我們使用jwt在使用者和伺服器之間傳遞安全可靠的訊息,他的主要使用場景為:認證與資料交換
#1 安裝JWT
在laravel根目錄下透過composer進行jwt擴充包的安裝,具體命令如下:
composer require tymon/jwt-auth
使用以下命令可以發布API 的設定檔到config 檔案下:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
2 設定JWT
在.env文件中產生jwt加密秘鑰,具體指令如下:
php artisan jwt:secret
修改config/api.php設定
'auth' => [ 'jwt' => 'Dingo\Api\Auth\Provider\JWT', ],
修改config/auth.php設定
'defaults' => [ #注:这里修改改了默认的配置,默认是web 'guard' => 'api', 'passwords' => 'users', ], 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'jwt', 'provider' => 'users', 'hash' => false, ], ],
關於jwt的詳細配置請查看相關文件:https://jwt-auth.readthedocs.io/en/develop/
3 相關程式碼示範
建立RefreshToken中間件,用於令牌過期刷新
namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; use Illuminate\Http\Request; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; use Tymon\JWTAuth\Exceptions\JWTException; use Tymon\JWTAuth\Exceptions\TokenExpiredException; use Tymon\JWTAuth\Http\Middleware\BaseMiddleware; class RefreshToken extends BaseMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle(Request $request, Closure $next) { // 检查此次请求中是否带有 token,如果没有则抛出异常。 $this->checkForToken($request); // 使用 try 包裹,以捕捉 token 过期所抛出的 TokenExpiredException 异常 try { // 检测用户的登录状态,如果正常则通过 if ($this->auth->parseToken()->authenticate()) { return $next($request); } throw new UnauthorizedHttpException('jwt-auth', '未登录'); } catch (TokenExpiredException $exception) { // 此处捕获到了 token 过期所抛出的 TokenExpiredException 异常,我们在这里需要做的是刷新该用户的 token 并将它添加到响应头中 try { // 刷新用户的 token $token = $this->auth->refresh(); // 使用一次性登录以保证此次请求的成功 Auth::guard('api') ->onceUsingId($this->auth->manager() ->getPayloadFactory() ->buildClaimsCollection() ->toPlainArray()['sub']); } catch (JWTException $exception) { // 如果捕获到此异常,即代表 refresh 也过期了,用户无法刷新令牌,需要重新登录。 throw new UnauthorizedHttpException('jwt-auth', $exception->getMessage()); } } // 在响应头中返回新的 token return $this->setAuthenticationHeader($next($request), $token); } }
User模型需要實作兩個方法:getJWTIdentifier()和getJWTCustomClaims()
<?php namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Tymon\JWTAuth\Contracts\JWTSubject; class User extends Authenticatable implements JWTSubject { use Notifiable; public $table = "user"; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password','phone','status','create_time','addr_id' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ // 'email_verified_at' => 'datetime', ]; /** * 指示是否自动维护时间戳 * * @var bool */ public $timestamps = false; public function getJWTIdentifier() { return $this->getKey(); } public function getJWTCustomClaims() { return []; } } ?>
建立UserController用於鑑權等相關操作
<?php namespace App\Http\Controllers\Api\V1; use App\Http\Controllers\Controller; use App\Models\User; use Dingo\Api\Routing\Helpers; use Illuminate\Http\Request; class UserController extends Controller { use Helpers; public function __construct() { //除去token验证的方法 $this->middleware('refresh.token', [ 'except' => [ 'login', ], ]); } /**用户登录 * @param Request $request * @return \Illuminate\Http\JsonResponse|void */ public function login(Request $request) { $phone = $request->get('phone'); $user = User::where('phone', $phone)->first(); // //attempt貌似无法验证其他字段,如需用其他字段鉴权使用login() // $credentials = request(['name','password']); // if (!$token = auth()->attempt($credentials)) { // return response()->json(['error' => 'Unauthorized'], 401); // } //只要是user实例就可以通过login鉴权 if (! $token = auth()->login($user)) { return response()->json([ "restful" => false, "message" => "账号错误", ]); } //获取用户信息 $user = $this->user(); $key = "user::info::".$user->id; //Redis缓存用户信息3600秒 Redis::set($key,serialize($user->original),"EX",3600); return $this->respondWithToken($token); } /**获取用户 * Get the authenticated User. * * @return \Illuminate\Http\JsonResponse */ public function user() { return response()->json(auth()->user()); } /**用户退出 * Log the user out (Invalidate the token). * * @return \Illuminate\Http\JsonResponse */ public function logout() { auth()->logout(); return response()->json(["message" => "退出成功"]); } /**用户登录状态刷新 * Refresh a token. * @return \Illuminate\Http\JsonResponse */ public function refresh() { return $this->respondWithToken(auth()->refresh()); } /**返回值 * @param $token * @return array */ protected function respondWithToken($token) { return [ 'access_token' => $token, 'token_type' => 'Bearer', 'expires_in' => auth()->factory()->getTTL() * 60, 'restful' => true ]; } }
以上是分析laravel8中的dingo與jwt鑑權的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Laravel的遷移系統在最新版本中提供了哪些新功能和最佳實踐? 1.新增了nullableMorphs()用於多態關係。 2.引入了after()方法來指定列順序。 3.強調處理外鍵約束以避免孤立記錄。 4.建議優化性能,如適當添加索引。 5.提倡遷移的冪等性和使用描述性名稱。

Laravel的最新版本引入了多個新功能:1.LaravelPennant用於管理功能標誌,允許分階段發布新功能;2.LaravelReverb簡化了實時功能的實現,如實時評論;3.LaravelVite加速了前端構建過程;4.新的模型工廠系統增強了測試數據的創建;5.改進了錯誤處理機制,提供了更靈活的錯誤頁面自定義選項。

SoftleteTeinElelelverisling -Memptry -BraceChortsDevetus -teedeeceteveveledeveveledeecetteecetecetecedelave

laravel10.xisthecurrentversion,offeringNewFeaturesLikeEnumSupportineloQuentModelsAndModersAndImpreverModeModeModelBindingWithenums.theSeupDatesEupDatesEnhanceCodereadability andSecurity andSecurity和butquirecareecarefulecarefulecarefulplanninganninganningalmplementAlimplemplemplemplemplemplempletationForupforupsupflade。

laravelmigrationsStreamLinedAtabasemangementbyallowingbolAlyChemachangeStobEdeDinedInphpcode,whobeversion-controllolleDandShared.here'showtousethem:1)createMigrationClassestodeFinePerationFineFineOperationsLikeCreatingingModifyingTables.2)

要查找最新版本的Laravel,可以訪問官方網站laravel.com並點擊右上角的"Docs"按鈕,或使用Composer命令"composershowlaravel/framework|grepversions"。保持更新有助於提升項目安全性和性能,但需考慮對現有項目的影響。

youshouldupdateTotheLateStlaravelVerverSionForPerformanceImprovements,增強的安全性,newfeatures,BetterCommunitySupport,and long-term-Maintenance.1)績效:Laravel9'Selover9'seloquentormoptimizatizationenenhanceApplicationsPeed.2)secuse:laravel8InIntrododeDodecter.2)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

禪工作室 13.0.1
強大的PHP整合開發環境

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器