I want to make my API unavailable to every client who doesn't have the token to access. This means the Android app will send a client as Android and token as token string in the header with keys client and token.
Now in middleware, I am checking it with my table fields to pass through authorization. If both match, then I will authorize and if don't then it will send a 403 response.
I am aware of Passport but it is not what I am looking for. In fact, consider it as a first layer of security and then use Passport as a second layer of security to authorize the API.
Is this code correct?
As I am not so familiar with Laravel - Middleware I just want to get some feedback from experts whether the code I have written is accurate and up to the standard. If not, I would appreciate your suggestion and help to make it better.
Middleware
namespace App\Http\Middleware;
use App\ApiToken;
use Closure;
use function response;
class ApiAccess
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle( $request, Closure $next ) {
if ( $this->checkToken( $request ) ) {
return $next( $request );
}
return response()->json( [ 'error' => 'Unauthorized' ], 403 );
}
public function checkToken( $request ) {
$client = $request->header( 'client' );
$token = $request->header( 'token' );
$checkToken = ApiToken::where( 'client', $client )
->where( 'token', $token )->first();
return $checkToken;
}
}
API Route
I am fetching results from the ApiToken table just to check:
Route::get('/', function(Request $request) {
return ApiToken::all();
})->middleware('apiAccess');
Optimized with Muhammad Nauman's answer here
public function checkToken( $request ) {
$client = $request->header( 'client' );
$token = $request->header( 'token' );
return ApiToken::where( 'client', $client )
->where( 'token', $token )->exists();
// Nicer, and it will return true and false based on the existence of the token and client.
}