如何使用 Laravel API 身份验证返回未经授权

use*_*002 6 api laravel

我正在使用带有令牌的 Laravel API 身份验证。(如此处所述:https : //laravel.com/docs/5.8/api-authentication#protecting-routes

我正在用 Postman 运行一些测试,它运行良好。当我尝试在没有有效令牌的情况下访问路由时,我看到响应是我的应用程序登录页面的(html)。如何返回Unauthorized消息而不是完整的登录页面?我是否必须创建自定义中间件?

控制器

class ExampleController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }

    public function show(Request $request) {
        return response()->json($request->user()->name);
    }
 }
Run Code Online (Sandbox Code Playgroud)

The*_*awk 12

对于使用Laravel 6 或更高版本(Laravel 8Laravel 10)的人
,请在内部添加“未经身份验证”的函数,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|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }

    // Add new method 
    protected function unauthenticated($request, array $guards)
    {
        abort(response()->json(
            [
                'api_status' => '401',
                'message' => 'UnAuthenticated',
            ], 401));
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 7

请在文件位置app/Exceptions/Handler.php的Handler类中添加方法

/**
 * 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)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest(route('login'));
}
Run Code Online (Sandbox Code Playgroud)

并在上面提到的同一个文件中的类上方添加以下行:use Illuminate\Auth\AuthenticationException;

在标题部分的邮递员中,请添加以下标题:X-Requested-With:XMLHttpRequest

希望这有助于并解决问题。谢谢。

  • 该句柄未经身份验证,但问题是关于未经授权的 (3认同)