So right now I'm using Laravel's default auth for api routes by doing this:
Route::group(['middleware' => ['auth:api']], function() {
...
}
The only thing with this is that it will throw a 401 if a non logged in user hits that page.
What I'm wondering is if there's a way to have a route that will login the user if a token is sent, but if not, they can still hit the api.
I know this will most likely be a custom Middleware, but I don't have a lot of experience with creating Middlewares so I'm not really sure where to start
EDIT
app/Http/Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:1000,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Fruitcake\Cors\HandleCors::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'admin' => \App\Http\Middleware\IsAdmin::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'cors' => \Fruitcake\Cors\HandleCors::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}
Here's a pretty simplified version of my routes api.php file
routes/api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::group(['prefix' => 'v2', 'middleware' => ['cors:api']], function() {
//routes that people need to be logged into to do
Route::group(['middleware' => ['auth:api']], function() {
Route::post('/comments/save/{type}/{id}', 'App\Http\Controllers\Api\v2\CommentController@save');
Route::get('/leagues/{id}', 'App\Http\Controllers\Api\v2\LeaguesController@get');;
});
Route::post('/auth/login', 'App\Http\Controllers\Api\v2\AuthController@login');
Route::post('/contact', 'App\Http\Controllers\Api\v2\ContactController@sendMessage');
});
Basically I'm wanting the ability to hit the /leagues/{id}
route with either a logged in user or a non logged in user. And if the user is logged in grab the user via Auth::user()
. If it helps at all, I'm using React for a front end and sending an api_token in the Authorization header like Bearer $token.
I figured out a way by creating my own custom Middleware. For anyone interested, here it is:
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
use App\Models\User;
class OptionalAuthenticate
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$header = $request->header('Authorization');
if(!empty($header)){
$token = str_replace('Bearer ', '', $header);
$user = User::where('api_token', '=', $token)->first();
if(!empty($user)){
Auth::login($user);
}
}
return $next($request);
}
}