2014-08-28 51 views
1

我想用laravel創建Web服務,但我不這樣做。我想用laravel創建Web服務

我使用的路線有一個人是這樣的:

Route::group(array('prefix' => 'api/v1', 'before' => 'basic.outh'), function(){ 

    Route::resource('url',  '[email protected]'); 
    Route::resource('show',  '[email protected]'); 
    Route::resource('destroy', '[email protected]'); 

}); 

但這路由過濾只想用戶名,例如:

Route::filter('auth.basic', function() 
{ 
    return Auth::basic("username"); 
}); 

我想使我的系統一樣笨的RESTful API。這個有可能?

你能告訴我任何例子嗎?

回答

6

是的,絕對有可能。

就個人而言,我建議使用OAuth2進行基於令牌的驗證,這更適合於API。 OAuth的學習曲線相當陡峭,但幸運的是,有一個Laravel(OAuth2包裝器)的包,使其非常容易,因爲它會爲您生成和驗證令牌。

套餐:
https://github.com/lucadegasperi/oauth2-server-laravel

例子:
我有一個類似的設置。下面的代碼並不意味着替換通過文檔,但這就像你的路線看起來像使用這個包裝。

Route::group(['prefix' => 'api/v1', 'before' => 'apiErrors'], function() 
{ 

    // Returns a valid token based on grant_type and credentials when a request is made to the accessToken endpoint. 
    // I use 'client_credentials' and 'refresh_token' for APIs serving mobile apps, for example. You can use that, or roll your own. 
    Route::post('accessToken', function() 
    { 

     return AuthorizationServer::performAccessTokenFlow(); 

    }); 

    // 'oauth' filter makes sure there is a valid token present 
    Route::group(['before' => 'oauth'], function() 
    { 
     // Your protected endpoints 
     Route::resource('url',  '[email protected]'); 
     Route::resource('show',  '[email protected]'); 
     Route::resource('destroy', '[email protected]'); 

    }); 

}); 
+0

太好了,非常感謝:) – hkucuk 2014-08-29 07:05:43

+0

@ c-griffin我們可以同時使用令牌csrf令牌和oauth2。 API表單的CSRF令牌和API的Oauth2令牌 – 2016-11-30 12:25:09

+0

通過oAuth規範,令牌傳遞到標題中。如果您使用的是https,則標頭將被加密。但總之,沒有任何東西可以阻止任何人使用oAuth和CSRF相互結合。 – 2016-12-05 23:06:06