我将使用JWTAuth从模型创建令牌。所以我用这个方法:
$token = JWTAuth::fromUser($user);
在我的api路线中,我有:
Route::post('login', 'AuthController@login');
Route::group([
'middleware' => 'jwt.auth',
'prefix' => 'auth'
], function ($router) {
Route::post('logout', 'AuthController@logout');
Route::post('refresh', 'AuthController@refresh');
Route::get('me', 'AuthController@me');
});
现在我应该有权从JWTAuth获取用户。然后我用:
$user = JWTAuth::parseToken()->authenticate();
但它返回false。
答案 0 :(得分:1)
您应该在api.php
Route::post('user', 'UserController@createUser');
并在您的控制器中
public function getAuthUser(Request $request) {
try {
if (!$user = JWTAuth::toUser($request->token)) {
return response()->json(['code' => 404, 'message' => 'user_not_found']);
} else {
$user = JWTAuth::toUser($request->token);
return response()->json(['code' => 200, 'data' => ['user' => $user]]);
}
} catch (Exception $e) {
return response()->json(['code' => 404, 'message' => 'Something went wrong']);
}
}
希望这会对你有所帮助。
答案 1 :(得分:0)
如果您需要从标头令牌中获取当前用户 ID,请尝试。已测试
use Tymon\JWTAuth\Facades\JWTAuth;
protected function getCurrentUser()
{
return JWTAuth::parseToken()->authenticate()->id;
}