简体   繁体   中英

Return JSON response instead of 401 Blade file

I am using AuthBasic for API authentication in a Laravel project, I have this problem: when the API request authentication is invalid instead of displaying the JSON response it returns the 401 default blade view template.

Here is the code:

app\\Http\\Middleware\\AuthBasic.php

public function handle($request, Closure $next)
{   
    if (Auth::onceBasic()) {
        return response()->json(["message", "Authentication Required!"], 401);
    } else {
        return $next($request);
    }
}

Remove the 401 or change it to 200 from this line:

return response()->json(["message", "Authentication Required!"], 401);

See the reference, the second parameter is defining the http code to send the browser. [401] in you case. https://laravel.com/api/5.7/Illuminate/Routing/ResponseFactory.html#method_json

This will fix your problem, probably!

public function handle($request, Closure $next)
{   
    $result = Auth::onceBasic();

    if($result === 401)
        return response()->json(["message", "Authentication Required!"]);
    else
        return $next($request);
}

So here is a half Solution for this problem:

vendor\\laravel\\framework\\src\\Illuminate\\Auth\\SessionGuard.php

    public function onceBasic($field = 'email', $extraConditions = [])
{
    $credentials = $this->basicCredentials($this->getRequest(), $field);

    if (! $this->once(array_merge($credentials, $extraConditions))) {
        //return $this->failedBasicResponse();
        return response()->json(["Message" => "Authentication Required!"], 401);
    }
}

So Instead of returning the Failed Basic Response it will return the JSON Message, but I don't want to make changes in Laravel Core Files, because in case of update they will get lost !

So Any Idea ?

Found the Solution:

app\\Exceptions\\Handler.php

public function render($request, Exception $exception)
{   
    if ($request->is('api/*') || $request->wantsJson())
    {
        $json = [
            'success' => false,
            'error' => [
                'code' => $exception->getCode(),
                'message' => $exception->getMessage(),
            ],
        ];
        return response()->json($json, 401);
    }
    return parent::render($request, $exception);
}

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