Reputation: 53
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);
}
}
Upvotes: 1
Views: 4047
Reputation: 29
Attached is a solution that doesn't require modifying any core files. Just use a try - catch block.
try {
$response = Auth::Basic();
//or $response = Auth::onceBasic();
}
catch (\Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException $e) {
return response()->json([
'message' => 'Authentication failed'
]);
}
return $next($request);
You can also use \Exception $e
to catch any type of exception, instead of only UnauthorizedHttpException.
Upvotes: 0
Reputation: 53
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 ?
Upvotes: 0
Reputation: 53
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);
}
Upvotes: 1
Reputation: 359
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);
}
Upvotes: 0
Reputation: 2621
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
Upvotes: 0