Skip to content
Advertisement

Laravel api route that grabs Auth::user() when Authorization is sent, but doesn’t hit 401 whenever you don’t

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 AppHttp;

use IlluminateFoundationHttpKernel 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 = [
        // AppHttpMiddlewareTrustHosts::class,
        AppHttpMiddlewareTrustProxies::class,
        FruitcakeCorsHandleCors::class,
        AppHttpMiddlewarePreventRequestsDuringMaintenance::class,
        IlluminateFoundationHttpMiddlewareValidatePostSize::class,
        AppHttpMiddlewareTrimStrings::class,
        IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            IlluminateSessionMiddlewareStartSession::class,
            // IlluminateSessionMiddlewareAuthenticateSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::class,
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],

        'api' => [
            'throttle:1000,1',
            IlluminateRoutingMiddlewareSubstituteBindings::class,
            FruitcakeCorsHandleCors::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => AppHttpMiddlewareAuthenticate::class,
        'admin' => AppHttpMiddlewareIsAdmin::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
        'can' => IlluminateAuthMiddlewareAuthorize::class,
        'cors' => FruitcakeCorsHandleCors::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
        'signed' => IlluminateRoutingMiddlewareValidateSignature::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
        'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
    ];
}

Here’s a pretty simplified version of my routes api.php file routes/api.php

<?php

use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;

/*
|--------------------------------------------------------------------------
| 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}', 'AppHttpControllersApiv2CommentController@save');

        Route::get('/leagues/{id}', 'AppHttpControllersApiv2LeaguesController@get');;
    });

    Route::post('/auth/login', 'AppHttpControllersApiv2AuthController@login');
    
    Route::post('/contact', 'AppHttpControllersApiv2ContactController@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.

Advertisement

Answer

I figured out a way by creating my own custom Middleware. For anyone interested, here it is:

<?php

namespace AppHttpMiddleware;

use Closure;
use Auth;
use AppModelsUser;

class OptionalAuthenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $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);
    }
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement