我正在尝试创建一个Laravel API项目。所以我在这个项目中设置了基本的laravel脚手架。在我的用户迁移中,我添加了:
$table->string('api_token', 60)->unique();
然后在我的User.php模型中添加了:
protected $fillable = [
'name', 'email', 'password','api_token'
];
然后在我的api.php中我做了一个测试路线:
Route :: group([' middleware' => [' auth:api']],function(){
Route::get('/test', 'ApiController@test');
});
在我的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 :(得分:1)
localhost/project1/public/index.php/api/test?api_token='hsvdvhvsjhvasdvas8871238'
会有所帮助。
如果您想要漂亮的网址,请阅读文档:Pretty URLs
答案 1 :(得分: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' => 'a@a.com',
'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'];
答案 2 :(得分: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); } }
protected $routeMiddleware = [
'autho' => \App\Http\Middleware\ApiAuthenticate::class,
];
{{1}}