2017-03-03 89 views
0

我正在嘗試創建一個Laravel API項目。所以我有這個基本的laravel腳手架搭建的項目。在我的用戶遷移我已經加入:Laravel API授權api_token

$table->string('api_token', 60)->unique(); 

然後在我的user.php的模型我已經補充說:

protected $fillable = [ 
    'name', 'email', 'password','api_token' 
]; 

然後在我的api.php我已經做了一個試驗路線:

路線::組([ '中間件'=> [ 'AUTH:API']],函數(){

Route::get('/test', '[email protected]'); 

}); 
在我Apicontroller

<?php 

namespace App\Http\Controllers; 

use Illuminate\Http\Request; 

class ApiController extends Controller 
{ 


public function test(Request $request){ 

return response()->json(['name' => 'test']); 


} 



} 

所以現在我鍵入:我api_token

localhost/project1/public/api/test?api_token='hsvdvhvsjhvasdvas8871238' 

這不是給我的JSON數據,而不是它重定向到主頁

+0

試試localhost/project1/test? – SteD

+0

thx SteD的答覆..我修好了。這是我犯的一個愚蠢的錯誤。沒有在路徑中包含/ api。但現在我有另一個問題,請參閱我編輯的問題。 – Mikethetechy

+1

@SteD對不起,它再次出現愚蠢的錯誤。我修好了:)再次抱歉,我的壞處應該是更耐心一點大聲笑。 – Mikethetechy

回答

1

localhost/project1/public/index.php/api/test?api_token='hsvdvhvsjhvasdvas8871238'將幫助記錄下來。

如果你想漂亮的網址,閱讀文檔:Pretty URLs

+0

thxx @gentcys。 – Mikethetechy

+0

通過GET參數發送令牌是不安全的做法。 –

0

你不會有,如果你使用Laravel 5.3或更高版本編寫自己的API中間件和路線。

此外,您可以使用內置的Passport包使用oAuth2來管理訪問令牌。

$http = new GuzzleHttp\Client; 

$response = $http->post($apiUrl.'oauth/token', [ 
    'form_params' => [ 
     'grant_type' => 'password', 
     'client_id' => '2', //this can be generated when you setup Passport package or using artisan commands 
     'client_secret' => 'xxxxxxxxx', //this can be generated when you setup Passport package or using artisan commands 
     'username' => '[email protected]', 
     'password' => 'test123', 
     'scope' => '', 
    ], 
]); 

$responseData = json_decode($response->getBody(), true); 

$token = $responseData['access_token']; //Now I have the token so I can call any protected routes 

$response = $http->request('GET', $apiUrl.'api/v1/user', [ 
    'headers' => [ 
     'Accept' => 'application/json', 
     'Authorization' => 'Bearer '.$token, 
    ], 
]); 

$responseData = json_decode($response->getBody(), true); 
echo "Name of the user is: ".$responseData['name']; 
+0

Thx tanay jha回覆。我試着按照護照文件。但它有點難,因爲它談論的是vue.js和gulp前端的東西。這很混亂。 – Mikethetechy

+0

@MohamedManas你並不需要使用Vue.js,只有當你希望你的前端基於Vue.js時才需要。看到我編輯的答案。 –

+0

thx解釋。看起來不錯。我會嘗試 – Mikethetechy

0

對於laravel 5.2
中間件/ ApiAuthenticate

namespace App\Http\Middleware; 

use Closure; 
use Illuminate\Support\Facades\Auth; 

class ApiAuthenticate 
{ 

    public function handle($request, Closure $next, $guard = null) 
    { 
     if (Auth::guard($guard)->guest()) { 
      return response()->json(['status'=>'error','message'=>'token mismatch']);; 
     } 
     return $next($request); 
    } 
} 


Kernel.php添加

protected $routeMiddleware = [ 
    'autho'  => \App\Http\Middleware\ApiAuthenticate::class, 
]; 


routes.php文件

 

    Route::group(['prefix'=>'api','middleware'=>'autho:api'], function(){ 
     Route::get('aaa','Api\[email protected]'); 
    });