Laravel Middleware Auth for API

16,639

Turns out I did need to make my own middleware which was easier than I thought:

<?php

namespace App\Http\Middleware;

use Auth;
use JWTAuth;
use Closure;

class APIMiddleware {

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next) {        
    try {
        $jwt = JWTAuth::parseToken()->authenticate();
    } catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
        $jwt = false;
    }
    if (Auth::check() || $jwt) {
        return $next($request);
    } else {
        return response('Unauthorized.', 401);
    }
}
}

Then I use this middleware on my api route group like so after registering in the kernel:

Route::group(['prefix' => 'api', 'middleware' => ['api.auth']], function() {
Share:
16,639
rosscooper
Author by

rosscooper

I am a full stack developer focussing on PHP, Laravel, React and Vue but I have also worked with a number of other languages and frameworks.

Updated on June 17, 2022

Comments

  • rosscooper
    rosscooper almost 2 years

    I am currently developing and application that has an API which I want to be accessible through middleware that will check if the user is authenticated using either Laravel's default Auth middleware and Tymone's JWT.Auth token based middleware so requests can be authenticated either of the ways.

    I can work out how to have one or the other but not both, how could I do this? I'm thinking I need to create a custom middleware that uses these existing middlewares?

    I am using Laravel 5.1

    Thanks

  • rosscooper
    rosscooper over 8 years
    This is correct but that will mean both middlewares have to pass rather than one or both.
  • Dippner
    Dippner over 8 years
    Ah, ok, I thought that was what you wanted, but I see now what you were after. Anyway, glad you worked it out!