在Laravel框架中,使用OAuth进行API认证通常涉及以下步骤:
- 安装Laravel Passport。
- 创建OAuth客户端。
- 使用Passport提供的中间件保护路由。
- 处理认证逻辑。
以下是一个简化的示例,展示了如何使用Laravel Passport进行OAuth认证:
首先,安装Laravel Passport:
composer require laravel/passport
然后,执行迁移创建Passport需要的数据库表:
php artisan migrate
接着,引入Passport的服务提供者并注册Passport的路由:
// config/app.php
'providers' => [
// ...
Laravel\Passport\PassportServiceProvider::class,
// ...
],
// ...
'aliases' => [
// ...
'Passport' => Laravel\Passport\Passport::class,
// ...
],
// 在AppServiceProvider中使用Passport::routes方法来注册Passport的路由
use Laravel\Passport\Passport;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
$this->registerRoutes();
// ...
}
public function register()
{
// ...
}
protected function registerRoutes()
{
if ($this->app->routesAreCached()) {
return;
}
Passport::routes();
// ...
}
}
最后,创建OAuth客户端并使用TokenGuard中间件保护API路由:
// 创建OAuth客户端
Artisan::command('passport:client --personal')
// 在app/Http/Kernel.php中使用Passport的TokenGuard中间件保护API路由
protected $routeMiddleware = [
// ...
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,
'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
'oauth.providers' => \Laravel\Passport\Http\Middleware\LoadOAuthProviders::class,
'oauth.clients' => \Laravel\Passport\Http\Middleware\LoadOAuthClient::class,
'token.can' => \Laravel\Passport\Http\Middleware\CheckTokenAccess::class,
];
// 使用TokenGuard中间件保护路由
protected $middlewareGroups = [
'web' => [
// ...
],
'api' => [
'throttle:60,1',
'bindings',
'oauth.providers',
'oauth.clients',
'token.can',
],
];
在创建用户时,确保用户模型实现了Laravel\Passport\HasApiTokens
trait:
\`