2017-03-03 84 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]'); 
    });