laravel - Laravel Passport 返回 403 错误而不是 route('login')
问题描述
我试图让 Laravel Passport 给客户一个403
响应,而不是route('login')
当他们尝试使用无效的授权令牌通过 REST 访问资源时。
这是我的route/api.php
Route::middleware(['auth:api'])->group(function () {
Route::prefix('invoices')->group(function () {
Route::post('', 'API\InvoiceController@create');
});
});
这是我的app/Http/Middleware/Authenticate.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
*/
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.phpunauthenticated
上的方法。
<?php
namespace App\Exceptions;
use Illuminate\Auth\AuthenticationException;
// ...
class Handler extends ExceptionHandler
{
// ...
/**
* Convert an authentication exception into an unauthenticated response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Auth\AuthenticationException $exception
* @return \Illuminate\Http\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
return response()->json(['error' => 'my custom message.'], 403);
}
}
推荐阅读
- spring-boot - Spring Boot 和 Couchbase 连接错误
- c# - 更改 assemblyVersion 将版本添加到 Application.LoadComponent 导致编译错误
- python - 如何将案例折叠的输出存储到 Python 中的数据框或列表中?
- java - 如何在 Android Studio 中单击时从列表中获取单词?
- reactjs - React Native:卸载动画
- xml - PowerShell XmlReader 到 XmlWriter,内联注释转移到新行
- python - Pandas df 返回 2 列实际总和的两倍
- c#-4.0 - BinaryFormatter .NETFramework 4.6.1 和 2.0 结果不同
- javascript - 如何在带有 google drive api 的 jquery 请求的函数中正确实现 async-await 或 then-catch
- reactjs - MUI 按钮悬停背景颜色和文本颜色