[英]Add custom middleware to Laravel Passport endpoints
I have a standard Laravel Passport setup on 5.4 - it all works fine and is generating tokens. 我在5.4上有一个标准的Laravel Passport设置 - 它一切正常并且正在生成令牌。
I protect my API routes using the auth:api middleware as well as a custom middleware that checks that specific headers in a request are present and valid before any requests are handled. 我使用auth:api中间件以及自定义中间件来保护我的API路由,该中间件在处理任何请求之前检查请求中的特定标头是否存在且有效。 This middleware works fine for the API routes group.
此中间件适用于API路由组。
Is there a way to wrap the Passport routes generated by laravel '.../oauth/token' in this middleware as well? 有没有办法将laravel'... / oauth / token'生成的Passport路由包装在这个中间件中?
Currently I have set up the routes in my AuthServiceProvider.php boot() method: 目前我已经在我的AuthServiceProvider.php boot()方法中设置了路由:
public function boot()
{
$this->registerPolicies();
// Passport/OAuth
Passport::routes(function ($router) {
$router->forAccessTokens();
$router->forTransientTokens();
});
Passport::tokensExpireIn(Carbon::now()->addDays(7));
Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
}
The end goal is that the oauth endpoints will return an error if the headers are not present. 最终目标是,如果标头不存在,oauth端点将返回错误。
你可以试试这个
Passport::routes(null, ['middleware' => 'api']);
In the app/Providers/AuthServiceProvider
include the Route facade by adding this use statement somewhere in the top: 在
app/Providers/AuthServiceProvider
,通过在顶部的某处添加此use语句app/Providers/AuthServiceProvider
包含Route facade:
use Illuminate\Support\Facades\Route;
Then on the boot()
method, put the Passport::routes() inside a Route::group() like this: 然后在
boot()
方法中,将Passport :: routes()放在Route :: group()中,如下所示:
Route::group(['middleware'=>'MyFunkyCustomMiddleware'], function(){
Passport::routes(); // <-- Replace this with your own version
});
Hope that helps! 希望有所帮助!
If you only need to add middleware to one Passport route for example /oauth/token
, you can do it this way: 如果您只需要将中间件添加到一个Passport路由(例如
/oauth/token
,则可以这样做:
php artisan r:l
php artisan r:l
查找您需要的路线 AccessTokenController@issueToken
AccessTokenController@issueToken
namespace App\\Http\\Controllers; use Illuminate\\Http\\Request; use Laravel\\Passport\\Http\\Controllers\\AccessTokenController; class ApiTokenController extends AccessTokenController { }
Route::middleware('MyMiddleware')->post('/api-token', 'ApiTokenController@issueToken');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.