namespace App\Providers;
use Dingo\Api\Auth\Auth;
use Dingo\Api\Auth\Provider\OAuth2;
use Illuminate\Support\ServiceProvider;
class OAuthServiceProvider extends ServiceProvider
{
public function boot()
{
$this->app[Auth::class]->extend('oauth', function ($app) {
$provider = new OAuth2($app['oauth2-server.authorizer']->getChecker());
$provider->setUserResolver(function ($id) {
// Logic to return a user by their ID.
});
$provider->setClientResolver(function ($id) {
// Logic to return a client by their ID.
});
return $provider;
});
}
public function register()
{
//
}
}
然后打开routes.php添加相关路由
//Get access_token
Route::post('oauth/access_token', function() {
return Response::json(Authorizer::issueAccessToken());
});
//Create a test user, you don't need this if you already have.
Route::get('/register',function(){
$user = new App\User();
$user->name="tester";
$user->email="test@test.com";
$user->password = \Illuminate\Support\Facades\Hash::make("password");
$user->save();
});
$api = app('Dingo\Api\Routing\Router');
//Show user info via restful service.
$api->version('v1', ['namespace' => 'App\Http\Controllers'], function ($api) {
$api->get('users', 'UsersController@index');
$api->get('users/{id}', 'UsersController@show');
});
//Just a test with auth check.
$api->version('v1', ['middleware' => 'api.auth'] , function ($api) {
$api->get('time', function () {
return ['now' => microtime(), 'date' => date('Y-M-D',time())];
});
});
分别创建BaseController.php和UsersController.php内容如下
//BaseController
namespace App\Http\Controllers;
use Dingo\Api\Routing\Helpers;
use Illuminate\Routing\Controller;
class BaseController extends Controller
{
use Helpers;
}
//UsersController
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
class UsersController extends BaseController
{
public function index()
{
return User::all();
}
public function show($id)
{
$user = User::findOrFail($id);
// 数组形式
return $this->response->array($user->toArray());
}
}