[英]laravel own api consumption from controller with bearer token
我喜歡通過Laravel中的api進行粗操作。 因此,兩個移動應用程序/ Web應用程序都可以在同一個api端進行原始操作。出於api安全目的,我使用護照。 我在使用郵遞員調用api end時很成功,而在嘗試從laravel控制器調用api end時卻得到了空輸出。 我正在嘗試使用不記名令牌。
前面有laravel刀片視圖,我在laravel中安裝了通行證。 我在api.php內創建了一些api端點,其中之一是/user/{id}
,其中啟用了auth:api中間件。
我有web.php
Route::get('profile', 'UserController@profile')->middleware('auth');
所以我的想法是從配置文件控制器發送帶有承載令牌的請求到/ api / user / 1
為了獲取承載令牌,我使用登錄控制器中的Request create /oauth/token
if (Auth::attempt(['email' => request('email'), 'password' =>
request('password')])) {
$user = Auth::user();
if(Auth::check()) {
$req = Request::create('/oauth/token', 'POST',[
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => 'WDv6wrY9Tf9HuixaiQjDWGy7yBqEG1IrmsLucAUI',
'username' => request('email'),
'password' => request('password'),
'scope' => '*'
]);
$res = app()->handle($req);
$responseBody = json_decode($res->getContent()); // convert to json object
return response()->json(['success' => $responseBody], $res->getStatusCode());
} else {
return response()->json(['error' => 'Not logged in '], 401);
}
}
它返回我不記名令牌。 我正在傳遞此承載令牌並嘗試從laravel配置文件控制器使用自己的api
$token ='eyJ0eXAiOiJKV1QiLCJhbGciOi...';
$req = Request::create('/api/user/1', 'GET',[
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$token,
],
]);
$res = app()->handle($req);
$profile_details = json_decode($res->getContent()); // convert to json object
return response()->json(['profile' =>$profile_details], $res->getStatusCode());
輸出是
{"profile":null}
status code
是302
當我通過post man
http://localhost:8000/api/user/1
打電話時
將授權承載令牌值設置為與以前相同
eyJ0eXAiOiJKV1QiLCJhbGciOi.....
我得到以下回應
{
"data": {
"id": 1,
"first_name": "rajib",
"last_name": "chow",
"address": "207 Eryn Coves",
"city": "South Treva",
"country": "Luxembourg",
"phone": "(397) 400-2302 x6997",
"fax": "82928",
"user_id": 1,
"created_at": "2019-06-26 15:03:31",
"updated_at": "2019-06-26 15:03:31"
}
}
我的api路線是
Route::get('/user/{id}', function ($id) {
return new UserResource(User::find($id)->customer);
})->middleware('auth:api');
如果我再次從代碼中刪除中間件('auth:api'),它將在我的控制器上正常工作
Route::get('/user/{id}', function ($id) {
return new UserResource(User::find($id)->customer);
});
以上給我預期的輸出
但是出於安全目的,我認為我應該將承載令牌與api調用一起傳遞。 如何從控制器發出API調用以及承載令牌
嘗試使用此代碼
$request = Request::create('/api/user/1', 'GET');
$request->headers->set('Accept', 'application/json');
$request->headers->set('Authorization', 'Bearer '.$token);
$res = app()->handle($request);
$profile_details = json_decode($res->getContent()); // convert to json object
return response()->json(['profile' =>$profile_details], $res->getStatusCode());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.