Laravel Passport返回403错误,而不是route('login')

问题描述 投票:0回答:1

我试图让Laravel Passport在尝试通过带有无效授权令牌的REST访问资源时,为客户提供403响应,而不是route('login')

这是我的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。

laravel laravel-passport
1个回答
0
投票

要将身份验证异常转换为未经身份验证的响应,可以在unauthenticated上覆盖/app/Exceptions/Handler.php方法。

<?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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.