简体   繁体   中英

How to properly return data with laravel sanctum?

I'm trying to add authentication to my api using laravel sanctum. My test route is:

Route::middleware('auth:sanctum')->get('/test', function () { return 'API OK'; });

This return "API OK" when authenticated. That's ok, but also adds additional information in html format. I only need the response. What am I missing here? This is a succesful case: 在此处输入图像描述

When token is invalid I'm rediredted to the login page. I just need the 401 error: 在此处输入图像描述 在此处输入图像描述

For the second part of your problem with an invalid token this answer helped me to override the sanctum response Customize laravel sanctum unauthorize response

The first part of your question when testing

Route::middleware('auth:sanctum')->get('/test', function () { return 'API OK'; });

I get API OK as the response, perhaps your config/sanctum.php or config/auth.php are misconfigured

you need to catch the exception to do it open app/http/exception/Handler.php and add this code in the register method

        $this->renderable(function (\Illuminate\Auth\AuthenticationException $e, $request) {
        if ($request->is('api/*')) {
            return response()->json([
                'message' => 'Unauthorized'
            ], 401);
        }
    });

I tied it and it worked for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM