当客户端尝试使用无效的Authorization令牌通过REST访问资源时,我正试图让Laravel Passport向客户端提供403
响应,而不是route('login')
响应。
这是我的route/api.php
Route::middleware(['auth:api'])->group(function () {
Route::prefix('invoices')->group(function () {
Route::post('', 'APIInvoiceController@create');
});
});
这是我的app/Http/Middleware/Authenticate.php
namespace AppHttpMiddleware;
use IlluminateAuthMiddlewareAuthenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param IlluminateHttpRequest $request
* @return string
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
//return route('login');
return response()->json([],403);
}
}
}
然而,redirectTo
给出了错误Header may not contain more than a single header, new line detected
。
我不确定在哪里设置403
响应?
我使用的是Laravel 5.8。
要将身份验证异常转换为未经身份验证的json响应,可以覆盖/app/Exceptions/Handler.php.上的unauthenticated
方法
<?php
namespace AppExceptions;
use IlluminateAuthAuthenticationException;
// ...
class Handler extends ExceptionHandler
{
// ...
/**
* Convert an authentication exception into an unauthenticated response.
*
* @param IlluminateHttpRequest $request
* @param IlluminateAuthAuthenticationException $exception
* @return IlluminateHttpResponse
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
return response()->json(['error' => 'my custom message.'], 403);
}
}
您可以使用这个:
<?php
namespace AppHttpMiddleware;
use IlluminateAuthMiddlewareAuthenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param IlluminateHttpRequest $request
* @return string|null
*/
protected function redirectTo($request)
{
if (!$request->expectsJson()) {
abort(response()->json('Unauthorized', 403));
}
}
}