Laravel护照返回403错误而不是路由("登录")



当客户端尝试使用无效的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));
}
}
}

相关内容

  • 没有找到相关文章

最新更新