Oct 5, 2017
0
Level 1
Basic validation for api user through custom guard without session
I want to create a middleware to do basic validation api users. In middle ware i want to use cutom guard. Here is my code. I have created a middleware named AuthApi.
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Factory as Basic;
class ApiAuth { /** * The Guard implementation. * * @var Guard */ protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
* @return void
*/
public function __construct(Basic $basic)
{
$this->auth = $basic;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, $guard='basicAuth')
{
if ($this->auth->guard($guard)->onceBasic()) {
return $next($request);
}else{
$data = ['error' => ['message' => 'Invalid credentials', 'status_code' => 401]];
return response()->json($data, 404, array(), JSON_PRETTY_PRINT);
}
}
}
This is the code i used to create a guard in config/auth.php
'basicAuth' => [ 'driver' => 'session', 'provider' => 'users', ],
It does not sent the json error message when user validation is false, so can someone please help me.
Please or to participate in this conversation.