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

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

如何創建具有用戶角色的 JWT 令牌(Spatie JWT Web 令牌)

如何創建具有用戶角色的 JWT 令牌(Spatie JWT Web 令牌)

PHP
一只名叫tom的貓 2022-07-09 10:39:23
我想在登錄后使用令牌傳遞用戶的角色。而不是像下面這樣傳遞 return response()->json([              'success' => true,             'access_token' => $token,            'token_type' => 'bearer',             'role' => auth('api')->user()->getRoleNames()            /* 'expires_in' => auth('api')->factory()->getTTL() * 60 */  ]);我想使用 JWT 令牌對用戶的角色進行編碼。我試過的 public function login()    {        $credentials = request(['email', 'password']);        if (! $token = auth()->guard('api')->attempt($credentials)) {            return response()->json(['errors' => 'In-valid username and Password'], 401);        }        return $this->respondWithToken($token);    }  protected function respondWithToken($token)    {        $role =auth('api')->user()->getRoleNames();        $payload = JWTFactory::make($role);         $token = JWTAuth::encode($payload);        return response()->json([              'success' => true,             'access_token' => $token,            'token_type' => 'bearer',        ]);    }當我嘗試這個時,我沒有得到令牌。我已經看過這個文檔https://github.com/tymondesigns/jwt-auth/wiki/Creating-Tokens來做到這一點。
查看完整描述

1 回答

?
慕妹3146593

TA貢獻1820條經驗 獲得超9個贊

在這里,我們需要使用用戶角色創建自己的令牌。對我有用的代碼可能對其他人有幫助。


 public function login()

    {

        $credentials = request(['email', 'password']);


        if (!auth()->guard('api')->claims(['role' => 'bar'])->attempt($credentials)) {

            return response()->json(['errors' => 'In-valid username and Password'], 401);

        }


        $token = auth('api')->claims(['role' => str_replace(['["', '"]', '/', '*'], '',auth('api')->user()->getRoleNames())])->attempt($credentials);

        return $this->respondWithToken($token);


    }


 protected function respondWithToken($token)

    {

        auth('api')->payload($token);

        return response()->json([  

            'success' => true, 

            'access_token' => $token,

            'token_type' => 'bearer',

        ]);

    }   


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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