亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 JWT 成功認證后如何觸發事件

使用 JWT 成功認證后如何觸發事件

PHP
慕田峪9158850 2022-07-09 18:17:38
我有一個 Laravel 版本 6 應用程序。我使用JWT 包進行身份驗證。路由定義如下:// route/api.phpRoute::middleware('auth:api')->group(function () {     Route::apiResources([        'genders' => 'API\GenderController'    ]);});在控制器內部,我有 5 個功能index、store、和。showupdatedestroy在這些函數中運行任何代碼之前,我需要為當前用戶設置語言環境,如下所示:public function index(){     $locale = request()->user()->lang;         app()->setLocale($locale);     // Rest of the function}我的控制器類擴展了一個BaseController類。由于 Restful API 是無狀態的,我需要在每次用戶發送 API 請求時設置語言環境?,F在的問題是,最好的地方在哪里,我該怎么做?我試圖在 BaseController 的構造函數中執行此操作,但似乎middleware('auth:api')尚未檢查構造函數中的令牌。另一個選項是在身份驗證事件處理程序中設置語言環境。我在這里找到了 JWT 包事件列表:// fired when the token could not be found in the requestEvent::listen('tymon.jwt.absent');// fired when the token has expiredEvent::listen('tymon.jwt.expired');// fired when the token is found to be invalidEvent::listen('tymon.jwt.invalid');// fired if the user could not be found (shouldn't really happen)Event::listen('tymon.jwt.user_not_found');// fired when the token is valid (User is passed along with event)Event::listen('tymon.jwt.valid');如果有人可以幫助我為我定義一個處理程序,tymon.jwt.valid我將不勝感激?;蛘呒词鼓衅渌鉀Q方案可以在執行index、store、show和函數update之前運行事件。destroy
查看完整描述

2 回答

?
慕姐8265434

TA貢獻1813條經驗 獲得超2個贊

我可以找到一種不同的方式來訪問構造函數類中的當前用戶。雖然request()->user()代碼在構造函數中返回 null,auth()->user()但即使在構造函數中也返回當前用戶。


abstract class BaseController extends Controller

{

    public function __construct() 

    {

        $locale = auth()->user()->lang;

        app()->setLocale($locale);

    }

}

因此,我可以在BaseController課堂上設置語言環境。


但是,我關于使用 JWT 事件的問題是開放的。另外,我想了解更多有關使用中間件的詳細信息,正如@patryk-karczmarczyk 在他的回答中所建議的那樣。


查看完整回答
反對 回復 2022-07-09
?
倚天杖

TA貢獻1828條經驗 獲得超3個贊

您可以在中間件中輕松完成。只需將驗證用戶身份的中間件放在設置位置的中間件之前。


創建您的路線類并在其中注冊App\Http\Kernel::$routeMiddleware


然后像這樣使用它:


// rouite/api.php


Route::group(['middleware' => ['auth:api', 'locale']], function () {

    Route::apiResources([

        'genders' => 'API\GenderController'

    ]);

});


查看完整回答
反對 回復 2022-07-09
  • 2 回答
  • 0 關注
  • 168 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號