Laravel Middleware Auth for API

萝らか妹 提交于 2019-12-06 06:16:00

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() {

I think you can use Route::group in your routes.php file and define the middlewares you want to use in an array.

Route::group(['middleware' => ['auth', 'someOtherMiddleware']], function()
{
    Route::get('api/somethinglist', function(){
       return App\Something::all();
    });
});

If I'm not mistaken all routes defined within that route group is checked against the middleware(s) you specify in the array.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!