我已经解决了这个问题,这就是我正在做的事情。Aso,我刚刚意识到这与cmac在他的回答中所做的非常相似。
api.php
Route::group(['middleware' => 'auth'], function () {
Route::get('/user', 'Auth\UserController@me')->name('me');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');
});
登录控制器.php
class LoginController extends Controller
{
use AuthenticatesUsers, ThrottlesLogins;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
// ...
/**
* If the user's session is expired, the auth token is already invalidated,
* so we just return success to the client.
*
* This solves the edge case where the user clicks the Logout button as their first
* interaction in a stale session, and allows a clean redirect to the login page.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$user = $this->guard()->user();
if ($user) {
$this->guard()->logout();
JWTAuth::invalidate();
}
return response()->json(['success' => 'Logged out.'], 200);
}
}
验证.php
class Authenticate extends Middleware
{
/**
* Exclude these routes from authentication check.
*
* Note: `$request->is('api/fragment*')` https://laravel.com/docs/7.x/requests
*
* @var array
*/
protected $except = [
'api/logout',
];
/**
* Ensure the user is authenticated.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
try {
foreach ($this->except as $excluded_route) {
if ($request->path() === $excluded_route) {
\Log::debug("Skipping $excluded_route from auth check...");
return $next($request);
}
}
// code below here requires 'auth'
{ catch ($e) {
// ...
}
}
我稍微过度设计了它。今天我只需要豁免/api/logout
,但我设置了逻辑以快速添加更多路线。如果您研究VerifyCsrfToken
中间件,您会发现它采用如下形式:
protected $except = [
'api/logout',
'api/foobars*',
'stripe/poop',
'https://www.external.com/yolo',
];
这就是为什么我把那个“注释”放在我上面的文档中。$request->path() === $excluded_route
可能不匹配api/foobars*
,但$request->is('api/foobars*')
应该。此外,一个人可能能够使用类似$request->url() === $excluded_route
的东西 match http://www.external.com/yolo
。