我已经使用$this->middleware('auth:api');
实现了中间件Authenticate。
该应用程序是REST API,因此我不需要Laravel来重定向客户端。我需要它来返回JSON响应。
redirectTo
中有一个方法App\Http\Middleware\Authenticate.php;
。此方法仅接受路由,因此无法将JSON响应添加到此方法。
当用户未通过身份验证时,如何使用中间件Authenticate (auth:api)
并返回JSON响应?
答案 0 :(得分:1)
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}
此类正在扩展Illuminate\Auth\Middleware\Authenticate
-并覆盖redirectTo
方法。您需要写下自己的handle方法。如果不需要框架的authenticate方法,可以删除extends
部分。
public function handle($request, Closure $next, ...$guards)
{
if (Auth::guest()) {
return response()->json(['message' => 'you shall not pass']);
}
// other checks
return $next($request);
}
如果需要基本类的某些功能,则另一种选择是保留extends
并在进行常规检查后调用父方法。
public function handle($request, Closure $next, ...$guards)
{
if (Auth::guest()) {
return response()->json(['message' => 'you shall not pass']);
}
return parent::handle($request, $next, $guards);
}
答案 1 :(得分:0)
当请求需要JSON响应时,Laravel已执行此操作。因此,只要您发送的是AJAX请求,或者您发送的请求的Accept
标头设置正确(application/json
或*
),Laravel就会自动以401 JSON进行响应响应。